글쓰는 개발자
[swift] 함수 / 클로저 표현식 본문
반응형
1. 함수
swift의 함수는 func로 시작한다
func hello() {
print("Hello")
}
매개변수를 받아 문자열을 리턴하는 함수
func printMessage(name: String, count: Int) -> String {
return("\(name) is \(count) years old")
}
함수가 단일 표현식을 가진다면 return 구문을 생략할 수 있다.
func printMessage(name: String, count: Int) -> String {
("\(name) is \(count) years old")
}
매개변수 앞에 따로 외부 매개변수명을 지정할수도 있다.
func printMessage(userName name: String, age count: Int) -> String {
("\(name) is \(count) years old")
}
let message = printMessage(userName: "Hello", age: 30)
print(message)
디폴트 매개변수도 선언할 수 있다.
func printMessage(userName name: String = "Kim", age count: Int) -> String {
("\(name) is \(count) years old")
}
let message = printMessage(age: 30)
print(message)
swift의 함수는 튜플로 여러 결과 값을 반환 할 수 있다.
func size(centimeter: Float) -> (centimeter: Float, millimeter: Float, meter: Float) {
return (centimeter, centimeter * 10, centimeter / 100)
}
let (centimeter, millimeter, meter) = size(centimeter: 100.0)
print(centimeter, millimeter, meter)
연속된 여러개의 매개변수를 받아서 처리하기 위해서는 ... 구문으로 된 가변 매개변수를 사용해야 한다.
func printMessage(messages: String...) {
for message in messages {
print(message)
}
}
printMessage(messages: "일", "이", "삼", "사")
외부 매개변수를 내부에서 변경하고 싶으면 inout 구문을 사용해야 한다.
inout을 사용한 매개변수에 들어갈 변수에는 앞에 참조의 표시인 &연산자를 붙여주어야 한다.
var val = 1
func add(_ value: inout Int) {
value += 10
}
print(val)
add(&val)
print(val)
// 결과값
1
11
2. 클로저 표현식
swift는 클로저 표현식을 사용해 다음과 같은 함수를 만들 수 있다.
let hello = { print("Hello") }
hello()
매개변수를 사용한 클로저 표현식은 다음과 같다.
let add = {(_ a: Int, _ b: Int) -> Int in
return a + b
}
print(add(10, 20))
반응형
'Development > swift' 카테고리의 다른 글
[swift] for-in 구문 / repeat while 반복문 / switch 구문 (0) | 2025.02.28 |
---|---|
[swift] 옵셔널 타입 / 삼항 연산자 / nil 병합 연산자 (0) | 2025.02.27 |
[swift] 문자열 데이터 타입 / 상수와 변수 / 튜플 (2) | 2025.02.27 |