[Swift] 클로저(Closure) - 2

팔랑이·2023년 6월 9일
0
post-thumbnail

23-05-19

후위 클로저 (Trailing Clousures)

함수의 마지막 인자가 클로저라면 이를 매우 짧게 축약할 수 있다.

func someFuncThatTakesAClousure(clousure: () -> Void){
    // body goes here
}


someFuncThatTakesAClousure(clousure: {
    // body goes here
})


someFuncThatTakesAClousure(){
    //body
}

앞서 살펴본 sorted(by:) 메소드 관련 식을 다음과 같이 trailing closure를 사용해 더 줄일 수 있다.

reversedNames = names.sorted(){$0 > $1}

reversedNames = names.sorted{$0 > $1}
// 괄호 생략 가능

map(_:) 메소드를 사용하는 코드의 길이를 줄여보는 예제

let digitNames = [
    0: "Zero", 1: "One", 2: "Two",   3: "Three", 4: "Four",
    5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {(number)-> String in
    var number = number
    var output = ""
    repeat {
        output = digitNames[number % 10]! + output
        number /= 10
    } while number > 0
    return output
} 
// "OneSix", "FiveEight", "FiveOneZero" 출력

위 예제에서, digitNames[number % 10]! 의 뒤에 느낌표가 붙어있는 것은 딕셔너리의 특정 key에 대한 값이 있을 수도 있고 없을 수도 있는 옵셔널이기 때문이다.


📚 참고도서
[SwiftUI 기반의 iOS 프로그래밍]

profile
정체되지 않는 성장

0개의 댓글