본문 바로가기
Smart Device/Swift

Swift 함수 #10 Function Type

by 언덕너머에 2015. 6. 2.

Function Type

함수의 이름을 빼고 파라미터로 사용하는 자료형과 리턴값의 자료형만으로 구성된 표현을 의미한다.


(자료형, 자료형, 자료형) -> 자료형

 : 세개의 파라미터를 받아서 하나의 리턴값을 리턴하는 함수라는 의미


-

func swapTwoInts(inout a: Int, inout b: Int) {

    let temporaryA = a

    a = b

    b = temporaryA

}

의 Function Type(함수 타입)은 다음과 같다.

(Int, Int) -> ()

 : 리턴값이 없는 경우에는 ()를 사용한다.


-

func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String {

    return s1 + s2 + joiner

}

의 Function Type(함수 타입)은 다음과 같다.

(String, String, String) -> String



예)

func addTwoInts(a: Int, b: Int) -> Int {

    return a + b

}


func multiplyTwoInts(a: Int, b: Int) -> Int {

    return a * b

}


var mathFunction: (Int, Int) -> Int = addTwoInts

println("mathFunction 결과: \(mathFunction(100, 200))")

  //-->mathFunction 결과: 300

mathFunction = multiplyTwoInts

println("mathFunction 결과: \(mathFunction(100, 200))")

  //-->mathFunction 결과: 20000