관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift 공식 문서] 6. Functions (함수) 본문

swift 공식 문서

[iOS - swift 공식 문서] 6. Functions (함수)

jake-kim 2021. 6. 23. 00:36

print(_:separator:terminator)

  • separator: 각 item 사이의 공간 space (디폴트 " ")
  • terminator: print안의 아이템들을 모두 출력 후 마지막 문자 (디폴트 '\n')

parameter에 함수 유형

  • 고차 함수(higher order function) 성격: 함수를 매개변수, 변수로 받을 수 있고 리턴 할 수 있는 성질
  • ex) 함수를 매개변수로 받는 형태
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
  • ex) 함수를 리턴하는 형태
let myFunction = chooseStepFunction(backward: true)
myFunction(1) // 0

func stepForward(_ input: Int) -> Int {
    return input + 1
}

func stepBackward(_ input: Int) -> Int {
    return input - 1
}

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    return backward ? stepBackward : stepForward
}

* 참고

https://docs.swift.org/swift-book/LanguageGuide/Functions.html

Comments