-
[4주차] Swift 문법 3iOS프로그래밍기초 2024. 9. 26. 15:57
1. 함수와 메서드(method)


스위프트에서는 argument와 parameter를 정확히 구분해야한다.
2. 함수 형태
func sayHello() -> Void { print("Hi") }1) 스위프트 함수는 func 로 시작한다
2) 호출위치는 위아래 상관없다
3) -> Void 로 리턴타입을 표현하고, void 리턴은 생략가능하다.
3. 호출
argument label 를 사용해야 한다.

4. 함수
함수
func add(x: Int , y: Int) -> Int{ return (x+y) } print(add(x: 10,y: 20)) //argument label var x : Int = add(x: 10,y: 20) print(x) print(type(of: add)) // (Int, Int) -> Int보이드 함수
func sayHello() { print("Hi") } print(type(of: sayHello)) //() -> ()5. 함수 매개변수에는 이렇게 넣을 수 도 있음
func add(first x: Int ,second y: Int) -> Int{ return (x+y) } print(add(first: 10,second: 20)) //argument label print(type(of: add)) // (Int, Int) -> Int
argument label 과 parameter name. // object - c 의 영향을 받았음
처음 argument labe 가 없던건 parameter name 가 전부 겸한형태
6. _생략
func add(_ x: Int ,_ y: Int) -> Int { // argument label가 필요없다. 생략 이렇게도 쓸 수 있다 return (x+y) } print(add(10,20)) print(type(of: add)) // (Int, Int) -> Int_ 로 생략을 의미하는 코드
7. 가장 많이 쓰는 방법
func add(_ x: Int ,with y: Int) -> Int { // argument label가 필요없다. 생략 이렇게도 쓸 수 있다 return (x+y) } print(add(10,with: 20)) print(type(of: add)) // (Int, Int) -> Int이렇게 섞어 쓰는 방법을 가장 많이 사용한다
애플에서 만든 코드들이 이따구로 만들어져있다.
object -c 형태를 swift로 변하는 과정에서 만든 형식

8. 스위프트에서 함수 이름
func add(_ x: Int ,with y: Int) -> Int { print(#function) // 함수 이름을 호출할 수 있음 // add(_:with:) return (x+y) } print(add(10,with: 20)) print(type(of: add)) // (Int, Int) -> Intfunc add(_ x: Int ,_ y: Int) -> Int { print(#function) // 함수 이름을 호출할 수 있음 // add(_:_:) return (x+y) } print(add(10, 20)) print(type(of: add)) // (Int, Int) -> Intfunc add(x: Int ,y: Int) -> Int { print(#function) // 함수 이름을 호출할 수 있음 // add(x:y:) return (x+y) } print(add(x: 10, y: 20)) print(type(of: add)) // (Int, Int) -> Int함수명(외부매개변수명:외부매개변수명: ...)
1) 스위프트함수명은 add 아님 add(x:y:) 임
2) 함수명에 , 없음
3) 매개변수만큼 : 있음
: 다음은 자료형
9. 함수형태 예제
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return items.count }자료형 // (UITableView, Int) -> Int
함수이름 // tableView(_:numberOfRowsInSection:)

10. guard 문
if문
var x = 1 while true { if x > 4 { break } // if문은 참일때 {}의 문장을 실행 print(x) //1 2 3 4, 조건(x<5)이 참일 때 실행 x = x + 1 }guard else 문
var x = 1 while true { guard x < 5 else { break } // 조건(x<5)이 거짓일 때 실행(break) // 반드시 else를 사용해야함 print(x) //1 2 3 4, 조건(x<5)이 참일 때 실행 x = x + 1 }이렇게 쓰는 문법은 아니다. 함수 안의 옵셔널 바인딩을 위해 쓴다.
func multiplyByTen(value: Int?) { guard let number = value else {//조건식이 거짓(nil)일 때 else 블록 실행 print("nil") return } print(number*10) //조건식이 참일 때 실행, 주의 : number를 guard문 밖인 여기서도 사용 가능 } multiplyByTen(value: 3) //30 multiplyByTen(value: nil) //nil multiplyByTen(value: 10) //1001) number는 {} 밖에서도 사용될 수 있다.
if let 문과 비교
func multiplyByTen(value: Int?) { if let number = value { print(number*10) } else { print("nil") } } multiplyByTen(value: 3) //30 multiplyByTen(value: nil) //nil multiplyByTen(value: 10) //100다중 if 문이 필요해짐
코드가 끝까지 내려가서 실행됨
func multiplyByTen(value: Int?) { guard let number = value else { return } //간단 2줄 print(number*10) //비교 if let number = value { print(number*10) } else { print("nil") } } multiplyByTen(value: 3) //30 multiplyByTen(value: nil) //nil multiplyByTen(value: 10) //100이처럼 옵셔널 바인딩을 풀때 guard를 훨씬 많이 쓰게된다.
11. 디폴트 매개변수

12. 함수로부터 여러 개의 결과 반환하기
func sss(x : Int, y : Int) -> (sum : Int, sub : Int, div : Double) { let sum = x+y let sub = x-y let div = Double(x)/Double(y) //같은 자료형만 연산 가능 return (sum, sub, div) } print(type(of: sss)) // 이 함수의 자료형 // (Int, Int) -> (sum: Int, sub: Int, div: Double) var result = sss(x:10,y:3) print(result.sum) print(result.sub) print(result.div)13. 2개의 정수를 입력받아 가감제 리턴
func displayStrings(strings: String...) //string으로 몇개를 넣어도 됨 // 가변 매개변수 { for string in strings { print(string) } } displayStrings(strings: "일", "이", "삼", "사") displayStrings(strings: "one", "two")14. inout매개변수:call by address 구현
var myValue = 10 func doubleValue (value: inout Int) -> Int { value += value return(value) } print(myValue) print(doubleValue(value : &myValue)) //출력 값? 레포트 print(myValue) //1. 스위프트는 기본적으로 매개변수를 받으면 상수로 취급한다. //2. 변경을 위해서는 2가지 방법 중 // 주소를 넘기고 받는 곳은 inout으로 받기 //. call by referance
15. BMI 계산 결과 판정
import Foundation //String(format: "%.1f", bmi) 를 사용하기 위해 func calcBMI (weight : Double, height : Double) { //Void형 let bmi = weight / (height*height*0.0001) // kg/m*m let shortenedBmi = String(format: "%.1f", bmi) switch bmi { case 0.0..<18.5: print("BMI:\(shortenedBmi),판정:저체중") case 18.5..<25.0 : print("BMI:\(shortenedBmi),판정:정상") case 25.0..<30.0 : print("BMI:\(shortenedBmi),판정:1단계 비만") case 30.0..<40.0 : print("BMI:\(shortenedBmi),판정:2단계 비만") default : print("BMI:\(shortenedBmi),판정:3단계 비만") } } calcBMI(weight:62.5, height: 172.3)출저 - 스마일한 스위프트
'iOS프로그래밍기초' 카테고리의 다른 글
[6주차] Swift 문법 5(클래스 failable initialize 상속) (1) 2024.10.10 [5주차] Swift 문법 4(일급시민 클로저 기초) (1) 2024.10.09 [3주차] Swift 문법 2 (0) 2024.09.19 [2주차] swift 문법 1 (1) 2024.09.12 [1주차] iOS 개요 (0) 2024.09.05