Swift 入門指南 V1.00 - 單元 8 範例




CH08.playground


func mathFunction(f: (Int, Int) -> Int, a: Int, b: Int) {
    println("The result is \(f(a, b)).")
}

mathFunction({(p1: Int, p2: Int) -> Int in
    return p1 + p2
}, 25, 63)

mathFunction({p1, p2 in return p1 + p2}, 26, 63)

mathFunction({p1, p2 in p1 + p2}, 27, 63)

mathFunction({$0 + $1}, 28, 63)

mathFunction(+, 29, 63)

func mathFunction2(a: Int, b: Int, f: (Int, Int) -> Int) {
    println("The result is \(f(a, b)).")
}
mathFunction2(30, 63) {$0 + $1}

// Trailing Closures
let d = [
    0: "零", 1: "一", 2: "二", 3: "三", 4: "四",
    5: "五", 6: "六", 7: "七", 8: "八", 9: "九"
]
let n = [32, 85, 101]
let s = n.map {
    (var i) -> String in
    var output = ""
    while i > 0 {
        output = d[i % 10]! + output
        i /= 10
    }
    return output
}

the end

沒有留言: