Swift

swift: 함수 데이터타입

소재훈 2021. 12. 27. 02:45

스위프트의 함수는 입금 객체이므로 하나의 데이터 타입으로 사용할 수 있다.

함수의 데이터 타입을 나타내는 방법은 다음과 같다.

(매개변수 타입의 나열) -> (반환 타입)

다음과 같은 함수들이 있을 때

func sayHello(name: String, times: Int) -> Stirng {
	...
}

func sayHelloToFriends(me: String, names: String...) -> String {
	...
}

func sayHelloWorld() {
	...
}

sayHello 함수의 타입은 (String, Int) -> String

sayHelloToFriends 함수의 타입은 (String, String...) -> String

sayHelloWorld 함수의 타입은 (Void) -> Void 타입이다.

Void 대신 빈 소괄호로 표현할 수도 있다.

 

typealias CalculateTwoInts = (Int, Int) -> Int

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}

func multiplyInts(_ a: Int, _ b: Int) -> Int {
    return a * b
}

var mathFunction: CalculateTwoInts = addTwoInts
print(mathFunction(2, 5))

mathFunction = multiplyInts
print(mathFunction(2, 5))

Int 값을 입력받아 계산 후 Int값을 돌려주는 형태의 함수를 CalculateTwoInts라고 표현하고 mathFunction이라는 변수에 해당 함수를 담고 있다. 함수는 일급 객체이므로 하나의 데이터 타입으로 사용할 수 있는 것이다.

 

다음과 같이 전달인자로 함수를 넘겨줄 수도 있다.

func printMathResult(_ mathFunction: CalculateTwoInts, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)

 

아래와 같이 반환 값으로 함수를 반환할 수도 있다.

func chooseMathFunction(_ toAdd: Bool) -> CalculateTwoInts {
    return toAdd ? addTwoInts : multiplyInts
}
printMathResult(chooseMathFunction(true), 3, 5)

 

'Swift' 카테고리의 다른 글

swift: 구조체  (0) 2022.01.21
swift: 옵셔널(Optional)  (0) 2022.01.21
swift: 함수와 매개변수  (0) 2021.12.27
swift: 함수의 정의와 호출  (0) 2021.12.27
스위프트의 데이터 타입  (0) 2021.10.08