개발/iOS
[Swift] 함수형 타입 Functional Type
마자용
2021. 8. 28. 18:23
🤓 아래 영상을 보고 참고했습니다 🤓
➜ 개발자 교양필수 : 1급 객체 함수. #스위프트 #클로저 제대로 이해하고 넘어가기.
✅ Swift에서의 자료형들 ...
1. 기본 타입 - String, Double, Int
func addTwoPoints(a: Int, b: Int) -> Int {
return a + b
}
2. 컬렉션 타입 - Array, Dictionary, Set
3. 클래스 타입 - UIView, UILabel, UITableView, CocoaTouch
✅ 그럼 함수형 타입은 ?!
함수 타입 - () -> Void, (Int, Int) -> Int
var mathFunction: (Int, Int) -> Int = addTwoPoints
mathFunction(2, 3) // 5
- 함수 = 1등 시민
- 어디로든 갈 수 있는 권리를 가짐
- 매개변수, 리턴타입, 할당, ...
- 어디로든 갈 수 있는 권리를 가짐
- 예시
func addVAT(source: Double) -> Double {
return source * 1.1
}
func couponDiscount(source: Double) -> Double {
return source * 0.9
}
func finalPrice(source: Double, additional: (Double) -> Double) -> Double {
let price = additional(source)
return price
}
let transAction = finalPrice(source: 38.5, additional: addVAT) // 38.5 * 1.1 = 42.35