천원의 개발

IOS Closure 축약순서 본문

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} // 후행 클로저로 바꿔~

'iOS&Swift🍎' 카테고리의 다른 글

IOS UIPickerView를 사용해보자  (0) 2022.03.26
IOS JSON 데이터 받아오기  (0) 2022.03.23
IOS 네트워킹  (0) 2022.03.22
IOS segue를 사용한 화면 전환  (0) 2022.03.21
IOS 버튼 3초 꾹눌렀을때 동작하게  (0) 2022.03.20