Swift/책 정리
[Swift] 함수(4) - 데이터 타입으로서의 함수
아잉으니야
2021. 1. 28. 21:48
[Swift] 함수(4) - 데이터 타입으로서의 함수
이 글은 Swift 프로그래밍 책을 읽고 요약한 내용입니다.
스위프트의 함수는 일급 객체이므로 하나의 데이터 타입으로 사용할 수 있다. 즉, 각 함수는 매개변수 타입과 반환 타입으로 구성된 하나의 타입으로 사용(정의)할 수 있다는 뜻이다.
(매개변수 타입의 나열) -> 반환 타입
func sayHello(name: String, times: Int) -> String {
// ...
}
sayHello
함수의 타입은 (String, Int) -> String
이다.
func sayHelloToFriends(me: String, names: String...) -> String {
// ...
}
sayHelloToFriends
함수의 타입은 (String, String...) -> String
이다.
만약 매개변수나 반환 값이 없다면 Void
키워드르 사용하여 없음을 나타낸다.
func sayHelloWorld() {
// ...
}
func sayHelloWorld() -> Void {
// ...
}
sayHelloWorld
함수의 타입은 (Void) -> Void
이다.
다음 표현은 모두 (Void) -> Void
와 같은 표현이다.
(Void) -> Void
() -> Void
() -> ()
함수의 축약 표현
sayHello(name: String, times: Int) -> String
함수의 경우sayHello(name:times)
와 같이 이름과 매개변수 개수 등을 이용해 함수를 표현할 수 있다.
typealias CalculateTwoInts = (Int, Int) -> Int
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
return a * b
}
var mathFunction: CalculateTwoInts = addTwoInts
// var mathFunction: (Int, Int) -> Int = addTwoInts 와 동일한 표현이다.
print(mathFunction(2, 5))
/* 7 */
mathFunction = multiplyTwoInts
print(mathFunction(2, 5))
/* 10 */
두 Int
값을 입력받아 계산 후 Int
값을 돌려주는 형태의 함수를 CalculateTwoInts
라는 별칭으로 지었다.
그리고 addTwoInts(_:_:)
와 multiplyTwoInts(_:_:)
라는 간단한 함수 두 개를 만들었다. 두 함수는 변수 mathFunction
에 번갈아가며 할당되거나 mathFunction
이라는 이름으로 호출할 수도 있다.
또, 전달인자로 함수를 넘겨줄 수도 있다.
func printMathResult(_ mathFunction: CalculateTwoInts, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
/* Result: 8 */
반환 값으로 함수를 반환할 수도 있다.
func chooseMathFunction(_ toAdd: Bool) -> CalculateTwoInts {
return toAdd ? addTwoInts : multiplyTwoInts
}
printMathResult(chooseMathFunction(true), 3, 5)
/* Result: 8 */