美文网首页程序员iOS Developer
Swift语法学习笔记3:函数与闭包

Swift语法学习笔记3:函数与闭包

作者: xueyuios | 来源:发表于2016-08-17 10:57 被阅读0次

本篇是《Swift语法学习笔记》系列的第三篇文章,将涵盖以下内容:

  • 函数和闭包
- 函数
    - 一般形式
    - 无参、无返回值的函数
    - 函数调用
    - 含有默认参数值的函数
    - 内部参数与外部参数
    - 内部参数与外部参数小节
        - 一个参数
        - 两个及以上参数
- 闭包
    - 函数变量
    - 函数变量作为参数
    - 闭包
    - 闭包的作用域

1 函数

1.1 一般形式

func areaOfRectangle(width: Double, height: Double) -> Double {
    return width * height
}

1.2 无参、无返回值的函数

func hello() {
    print("Hello, world")
}

或者

func hello() -> Void {
    print("Hello, world")
}

1.3 函数调用

一般无需提供第一个参数的名称(1.5小节会详细解释)

let area = areaOfRectangle(20, height: 10)

1.4 含有默认参数值的函数

功能描述:使用分隔符delimiter将传入的字符串分割成字符串数组,默认分隔符为空格:

func separateWords(str: String, delimiter: String = " ") -> [String] {
    return str.componentsSeparatedByString(delimiter)
}

使用方法:

let result = separateWords("One small step")
print(result)     // [One, small, step]

或者

let result = separateWords("One. Two. Three", delimiter: ". ")     // "delimiter" is required
print(result)     // [One, Two, Three]

1.5 内部参数与外部参数

下面的例子中,width与height是外部参数,用于函数调用;w和h是内部参数,用于函数内部使用:

func areaOfRectangle(width w: Double, height h: Double) -> Double {
    return w * h
}

调用方法:

let area = areaOfRectangle(width: 20, height: 10) 

Swift automatically supplies an external name for an argument with a default value, making it the same as the internal name (although you can override this by supplying your own external name). That means that the argument name must be used if its value is not defaulted.

可以将外部参数设置为空:

func separateWords(str: String, _ delimiter: String = " ") -> [String] {
    return str.componentsSeparatedByString(delimiter)
}
let result = separateWords("One. Two. Three", ". ")
print(result)

1.6 内部参数与外部参数小结

  • 一个参数
  • 两个以上参数
    未指定外部参数(参考1.1小节)。调用时无需指定第一个参数的名字(编译器已经为第一个参数指定了默认空的外部参数名称),但是必须指定第二个参数的外部参数名字(编译器会自动创建第二个参数的外部名字和内部名字一样);
    指定了外部参数名字。调用时就必须指定外部参数名字;
    指定外部名字为空“-”,调用时无需指定参数名字。

    func areaOfRectangle(w: Double, _ h: Double) -> Double {
    return w * h
    }
    let area = areaOfRectangle(20, 10)

编译器默认第一个参数的外部参数为空,除非用户指定了非空外部参数名字:

func areaOfRectangle(_ w: Double, _ h: Double) -> Double {     // OK, but gets a warning
    return w * h
}

2 闭包

2.1 函数变量

In Swift, functions are types, so you can create a variable of function type, assign a reference to a function to it, and use that variable to call the function. Similarly, you can pass a function as an argument to another function or return a function from a function.

声明一个输入参数为Double类型,返回值为Double类型的函数变量:

var operation: (Double) -> Double

或者

var operation: Double -> Double

使用该函数变量:

func doubleMe(number: Double) -> Double {
    return 2 * number
}
operation = doubleMe
operation(2)         // Result is 4

指向另外一个函数:

func quadrupleMe(number: Double) -> Double {
    return 4 * number
}
operation = quadrupleMe
operation(2)         // Result is 8

2.2 函数变量作为参数

首先,需要定义一个函数:

func compareInts(first: Int, second: Int) -> Bool {
    return first < second
}

创建函数变量,并传递到函数内部:

var values = [12, 3, 5, -4, 16, 18]
let sortedValues = values.sort(compareInts)
sortedValues         // Result: [-4, 3, 5, 12, 16, 18]

或者

var values = [12, 3, 5, -4, 16, 18]
values.sortInPlace(compareInts)
values     // Result: [-4, 3, 5, 12, 16, 18]

2.3 闭包

将2.2小节中的函数声明、函数变量定义与函数变量的传递合并在一起:

var values = [12, 3, 5, -4, 16, 18]
    let sorted = values.sort({(first: Int, second: Int) -> Bool in
    return first < second
})

或者

let sorted = values.sort() { // The closure is now outside the parentheses
    (first: Int, second: Int) -> Bool in
    return first < second
}

或者

let sorted = values.sort() {
    first, second in // Swift infers the argument types and return type!
    return first < second
}

或者

let sorted = values.sort() { return $0 < $1 }

甚至

let sorted = values.sort() { $0 < $1 }

2.4 闭包的作用域

func getInterestCalculator(rate: Double) -> (Double, Int) -> Double {
    let calculator = {(amount: Double, years: Int) -> Double in rate * amount * Double(years)}
    return calculator
}

调用

let calculator = getInterestCalculator(0.05)
calculator(100.0, 2)     // Result is 10: interest at 5% on $100 over 2 years.

参考文献

《Beginning iPhone Development with Swift 2 - Exploring the iOS SDK 》From page 777 to page 838.

联系作者

相关文章

  • swift学习笔记 ⑥ —— 闭包

    Swift学习笔记 - 文集 闭包,就是能够读取其他函数内部变量的函数。Swift 中的闭包与 C 和 OC 中的...

  • Swift学习笔记(1)

    SWift学习笔记 闭包 闭包表达式 闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift 中的闭包与 ...

  • Swift 闭包

    闭包是特殊的函数 Swift 中,闭包其实是一个特殊的函数,匿名函数 输出 闭包语法 简写: 简写规则: 如果是单...

  • Swift语法学习笔记3:函数与闭包

    本篇是《Swift语法学习笔记》系列的第三篇文章,将涵盖以下内容: 函数和闭包 1 函数 1.1 一般形式 1.2...

  • 使用Playground快速练习Swift语法--闭包和枚举

    闭包 定义:闭包是自包含的函数代码块,可以在代码中被传递和使用。 闭包表达式语法 Swift闭包使用{}包含,in...

  • 学习笔记---Swift函数与闭包

    1.Swift中分为四种函数 1.1 无参数无返回值 1.2. 无参数有返回值 1. ...

  • Swift 学习笔记 - 函数与闭包

    函数 使用函数类型 (Using Function Types) 函数类型作为参数类型 (Function Typ...

  • swift4 闭包

    swift 闭包 闭包:swift 中 函数是闭包的一种类似于oc的闭包闭包表达式(匿名函数) -- 能够捕获上下...

  • swift语法--12-1闭包基本概念

    swift语法--12-1闭包基本概念 block和闭包区别 OC:block类似于匿名函数, 用于封装代码块, ...

  • Swift-闭包

    Swift 闭包 函数 ()->() Swift 中的闭包和 Objective-C 中的 block 类似,闭包...

网友评论

    本文标题:Swift语法学习笔记3:函数与闭包

    本文链接:https://www.haomeiwen.com/subject/cpjmsttx.html