ABOUT ME

iOS, Swift 개발 블로그입니다.

Today
Yesterday
Total
  • Swift - Function Notation, Function Type
    Programming/Swift 2020. 10. 9. 23:24

     

     

    오늘은 함수를 부르는 방법인 Function Notation과 함수의 형식인 Function Type에 대해서 공부해 보겠습니다.

     


     

    Function Notation

     

    함수를 호출하는 게 아니라 함수를 표기하는 방법입니다.

    함수 표기 방법을 왜 알아야 할까요???

    공식문서를 볼 때나 상수나 변수에 함수를 저장할 때 Function Natation이  사용됩니다.

     

     

     

    funcName
    funcName(label:label:)

     

    Parameter가 없거나 ArgumentLabel을 _로 생략한 경우에는 funcName 만 적어줍니다.

    _로 생략한 경우 funcName(_:)과 같이 나타낼수도 있습니다.

    funcName()으로 적으면 이건 함수 호출 식이죠? 헷갈리지 않게 주의해주세요.

     

     

     

    func sayGreeting() {
    print("Good afternoon")
    print("good evening")
    print("good night.")
    }
    let a = sayGreeting
    a()

     

    상수 a에 함수 sayGreeting을 저장했습니다. 함수를 호출한 표현식을 저장한 게 아니죠!

    이렇게 상수에 저장했다면 a()로 함수를 호출할 수 있습니다.

     

     

     

    func add(a: Int, b: Int) -> Int {
    return a + b
    }
    var b = add(a:b:)
    b(10, 20) // 30
    b(a: 10, b: 20) // Error!!
    view raw add(a:b:).swift hosted with ❤ by GitHub

     

    관계가 없는 아규먼트레이블을 사용했다는 에러메세지가 출력됩니다.

    다음은 파라미터가 존재하는 함수입니다.

    여기서 주목할 점은 add(a:b:) 함수를 저장한 b를 이용하여 함수를 호출할 때 ArgumentLabel을 사용하면 에러가 발생한 다는 점입니다.

    오히려 ArgumentLabel를 사용하지 않은 표현식은 에러가 발생하지 않았습니다.

    왜 이럴까요??

    그 이유는 FunctionType과 관련이 있습니다!

    Function Type을 설명하고 이유를 알려드리겠습니다.

     


     

    Function Type

     

    Swift에서 함수는 First Class Citizen입니다.

    First Class Citizen은 간단히 세 특징만 기억해 주세요!

    1. 상수나 변수에 저장할 수 있다.
    2. Parameter로 전달할 수 있다.
    3. 함수에서 Return 할 수 있다.

    이 세 특징을 가지려면 Type이 있어야 합니다. 함수는 First Class Citizen이기 때문에 Type을 가집니다.

     

     

     

    (ParameterType) -> ReturnType

     

    함수의 타입은 ParameterType과  ReturnType으로 나타냅니다.

    만약 Parameter가 없는 함수라면 ParameterType을 ()로 표현합니다.

    그리고 ReturnType이 없다면 Void 또는 ()로 표현합니다.

    Void는 Return Type이 없다. 를 나타내는 Keyword입니다.

     

     

     

    func sayGreeting() {
    print("Good afternoon")
    print("good evening")
    print("good night.")
    }
    type(of: sayGreeting) // () -> ()

     

    그래서 sayGreeting함수의 타입은 () -> () 혹은 () -> Void입니다.

     

     

     

    type(of: add(a:b:)) // (Int, Int) -> Int

     

    Parameter가 여러 개 있는 함수는 , (comma)로 구별하여 나타냅니다.

     

    그럼 Function Type에 주목해주세요! 여기에 ArgumentLabel이 포함되나요???

    오로지 ParameterType과 Return Type만 있죠?

    이렇기 때문에 함수를 상수나 변수에 저장하고 호출할 때 ArgumentLabel을 사용하면 에러가 발생하게 됩니다.

     

    var b = add(a:b:) 여기서 ArgumentLabel을 저장하고 있잖아!?!라고 생각하실 수도 있습니다.

    하지만 여기서 add(a:b:)는 함수를 부르는 방식이지 a:b: ArgumentLabel을 b에 저장하는 게 아닙니다!

     

     

     

    func addNumbers(num: Int...) -> Int {
    var result = 0
    for i in num {
    result += i
    }
    return result
    }
    type(of: addNumbers(num:)) // (Int...) -> Int

     

    Variadic Parameter를 사용하는 함수라면 (Int...) -> Int과 같이 ParameterType뒤에 ...을 붙여줍니다.

     

     

     

     

    func swapNum(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
    }
    type(of: swapNum) // (inout Int, inout Int) -> ()

     

    In-out Parameter를 사용했다면 (inout Int, inout Int) -> ()와 같이 ParameterType앞에 inout을 붙여줍니다.

     


     

    Function을 Return 하는 Function의 Type

     

    함수는 First Class Citizen이기 때문에 함수에서 Return 할 수 있다고 했죠?

    그럼 함수를 리턴하는 함수의 Type은 어떻게 표시할까요?

     

    func add(a: Int, b: Int) -> Int {
    return a + b
    }
    func subtract(a: Int, b: Int) -> Int {
    return a - b
    }
    func selectOperator(op: String) -> (Int, Int) -> Int {
    if op == "+" {
    return add(a:b:)
    } else {
    return subtract(a:b:)
    }
    }
    type(of: selectOperator(op:)) // (String) -> (Int, Int) -> Int

    타입만 확인하기 위해 간단하게 함수를 구현했습니다.

    FunctionType은 (ParameterType) -> ReturnType 이였죠?

    여기서 ReturnType이 또 FunctionType이기 때문에 (ParameterType) -> (ParameterType) -> ReturnType 이렇게 표현됩니다.

    selectOperator(op:) 함수는 String을 Parameter로 받아 (Int, Int) -> Int 함수를 리턴하므로 (String) -> (Int, Int) -> Int Type 함수가 됩니다.

     

    -> 가 여러 개 나와서 조금 헷갈릴 수도 있습니다.

    -> 가 여러 개 있으면  처음 -> 를 먼저 찾는 게 중요합니다. 그러고 그 이후에 나오는 Type을 따로 생각해주시면 됩니다.

    (Int, Int) -> Int를 따로 떼어놓고 본다면 Int 두 개를 받아 Int를 리턴하는 함수를 리턴하는구나 생각하면 쉽습니다.

     

     


     

    참고자료

     

    https://kxcoding.com

     

    여러분의 새로운 도전을 응원합니다 | KxCoding

    Mastering SwiftUI 더 적은 코드로, 더 멋진 UI 만들기

    kxcoding.com

     

     

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

     

    Functions — The Swift Programming Language (Swift 5.6)

    Functions Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed. Swift’s unified function syntax

    docs.swift.org

     

     

     

    728x90

    'Programming > Swift' 카테고리의 다른 글

    Swift - Tuple  (0) 2020.10.12
    Swift - Closure  (1) 2020.10.11
    Swift - Function Variadic, In-out Parameter  (0) 2020.10.08
    Swift - Function Parameter  (0) 2020.10.07
    Swift - Function Basic  (0) 2020.10.06
Designed by Tistory.