範例一 ++

override func viewDidLoad() {
    super.viewDidLoad()
    let total = add(5)(11)
}

Currying

func add(_ number:Int) -> (Int) -> Int {
    return {
        count in
        return count + number
    }
}

結果

number = 5
count = 11
total =16

count 會接到 (Int)回傳值
也就是第二個(11)

傳入三個變數

let total = add(5)(11)(18)
func add(_ number:Int) -> (Int) -> (Int) -> Int {
    return {
        count in return{
            count2 in return count + number + count2
        }
    }
}
number = 5
count = 11
count2 = 18
total =34

範例二 比較大小

if greaterThan(10)(20) {
    print("大於")
}else{
    print("小於")
}
func greaterThan(_ comparer: Int) -> (Int) -> Bool {
    return { $0 < comparer }
}

結果

comparer = 10
$0  = 20
小於

Categorized in: