Swift 易忽略的笔记 4):Function & Closure

来源:互联网 发布:点对点网络测速工具 编辑:程序博客网 时间:2024/05/02 00:59

1. func

External Parameter Names:  方便阅读,类似OC的method,每个变量前都有说明符,赞

func join(string s1: String, toString s2: String, withJoiner joiner: String)    -> String {        return s1 + joiner + s2}

join(string: "hello", toString: "world", withJoiner: ", ")// returns "hello, world”


“Shorthand External Parameter Names”: 提示符和Parameter变量名一样
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {    for character in string {        if character == characterToFind {            return true        }    }    return false}
let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")// containsAVee equals true, because "aardvark" contains a "v”


Variadic Parameters:

func arithmeticMean(numbers: Double...) -> Double {    var total: Double = 0    for number in numbers {        total += number    }    return total / Double(numbers.count)}arithmeticMean(1, 2, 3, 4, 5)// returns 3.0, which is the arithmetic mean of these five numbersarithmeticMean(3, 8, 19)// returns 10.0, which is the arithmetic mean of these three numbers”

“Constant and Variable Parameters”

func alignRight(var string: String, count: Int, pad: Character) -> String {    let amountToPad = count - countElements(string)    for _ in 1...amountToPad {        string = pad + string    }    return string}let originalString = "hello"let paddedString = alignRight(originalString, 10, "-")// paddedString is equal to "-----hello"// originalString is still equal to "hello”

In-Out Parameters:相当于按引用传递

func swapTwoInts(inout a: Int, inout b: Int) {    let temporaryA = a    a = b    b = temporaryA}”

var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")// prints "someInt is now 107, and anotherInt is now 3”

Function Type

var mathFunction: (Int, Int) -> Int = addTwoInts”

function type as return type

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {    return backwards ? stepBackward : stepForward}”

Nested Function:

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {    func stepForward(input: Int) -> Int { return input + 1 }    func stepBackward(input: Int) -> Int { return input - 1 }    return backwards ? stepBackward : stepForward}var currentValue = -4let moveNearerToZero = chooseStepFunction(currentValue > 0)// moveNearerToZero now refers to the nested stepForward() functionwhile currentValue != 0 {    println("\(currentValue)... ")    currentValue = moveNearerToZero(currentValue)}println("zero!")// -4...// -3...// -2...”



2. Closure

Closure Expression Syntax

{ (parameters) -> return type in    statements}

reversed = sort(names, { (s1: String, s2: String) -> Bool in    return s1 > s2    })

“Inferring Type From Context” 也就是说,作为函数的参数时候,这些类型可以省略

reversed = sort(names, { s1, s2 in return s1 > s2 } )

reversed = sort(names, { $0 > $1 } )

reversed = sort(names, >)


Trailing Closures: 

func someFunctionThatTakesAClosure(closure: () -> ()) {    // function body goes here} // here's how you call this function without using a trailing closure: someFunctionThatTakesAClosure({    // closure's body goes here    }) // here's how you call this function with a trailing closure instead: someFunctionThatTakesAClosure() {    // trailing closure's body goes here}

reversed = sort(names) { $0 > $1 }




例子:

let digitNames = [    0: "Zero", 1: "One", 2: "Two",   3: "Three", 4: "Four",    5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]let numbers = [16, 58, 510]

let strings = numbers.map {    (var number) -> String in    var output = ""    while number > 0 {        output = digitNames[number % 10]! + output        number /= 10    }    return output}// strings is inferred to be of type String[]// its value is ["OneSix", "FiveEight", "FiveOneZero"]




0 0
原创粉丝点击