iOS&Swift🍎

IOS Closure 축약순서

천 원 2022. 3. 23. 03:20

오늘은 정말 정말 햇갈리는 closure를 만드는 법을 순서대로 정리 해보았다!

func calculator (n1: Int, n2: Int, operation: (Int, Int) -> Int ) -> Int {
    return operation(n1, n2)
}

func add(n1: Int, n2: Int) -> Int { // 기본형태
    return n1 + n2
}
//func랑 함수이름 지우고~ { 앞으로 빼고 그자리에 in 써주면 끝!
calculator(n1: 2, n2: 3, operation: {(n1: Int, n2: Int) -> Int in  // closure만듬
    return n1 + n2
})
//type 유추를 하라 하고 자료형들 지워주고~
calculator(n1: 2, n2: 3, operation: {(n1, n2) in  // 자료형 지움
    return n1 + n2
})

calculator(n1: 2, n2: 3, operation: {(n1, n2) in n1 + n2 }) // 걍 리턴도 지워!
//$0은 첫번째 매개변수, $1은 두번째 매개변수
calculator(n1: 2, n2: 3, operation: {$0 + $1}) // 달러로 바꿔!

calculator(n1: 2, n2: 3) {$0 + $1} // 후행 클로저로 바꿔~