9. Swift 中的函数

来源:互联网 发布:雅思7分有多难 知乎 编辑:程序博客网 时间:2024/05/18 15:26

在Swift 中, 函数的声明和Objective-C有些不同, 下面让我们来看看.


1.无参函数

func personInfo() {    // body}

这种函数是不需要返回任何值, 直接调用即可.


2.带参带返回值函数

func personInfo(name: String) -> String {    return name}

这种函数, name就是需要传入的参数, ->String 就是所返回的值, 函数参数的多少就看个人的需要了, 默认函数的参数是为Let类型, 是不可变的.


3.可变参数函数

func personInfo(var name: String) -> String {    name = "xiaoming"    return name}

这种函数的参是可变的, 但需要注意, 无论你传入进来的name是什么值, 只要函数内经过修改, 就和你所传入进来的参数不同.


4.带默认参数的函数

func personInfo(name: String = "xiaoming") -> String {    return name}

这种函数默认就有一个值, 可为let类型, 也可以为var类型, 看个人需求.


5.返回值为元组类型的函数

func personInfo() -> (name: String, age: Int) {    let name = "xiaoming"    let age = 20    return (name, age)}

这种函数可以返回一个元组, 比如我们传入一个个人信息的结构体, 但我们只需要获取其中的某几个信息, 就可以这么做了.


6.可变参函数

func studentAverageScore(scores: Double...) -> Double {    var result: Double = 0    for score in scores {        result += score    }    return result / Double(scores.count)}print(studentAverageScore(50, 90, 50))// 输出的结果为: 63.3333333333333

由于我这里没有做保留小数的限制, 所以默认保留Double可显示的小数.


7.函数的类型

func stepForward(input: Int) -> Int {    return input + 1}func stepBackward(input: Int) -> Int {    return input - 1}func chooseStepFunction(backwards: Bool) -> (Int) -> Int {    return backwards ? stepBackward : stepForward}var currentValue = 3let moveNearerToZero = chooseStepFunction(currentValue > 0)print("Counting to zero:")while currentValue != 0 {    print("\(currentValue)...")    currentValue = moveNearerToZero(currentValue)}print("zero!")// 输出的结果为: // Counting to zero:// 3...// 2...// 1...// zero!

这里的chooseStepFunction函数, -> (Int) -> Int, 是为了限制所返回的函数必须是参数, 返回值都为Int类型, 否则就会报错.

我们也可以把函数嵌套在一个函数内, 但这样做, 外部就不能调用里面的函数, 比如:

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}

8.函数的参数名

在设置函数的参数名, 我们有好几种做法, 第一种就是默认参数名的设置, 第二种就是把参数别名用下标的方法隐藏掉, 第三种就是给参数名设置别名.

func personInfo(name: String, age: Int, height: Int, weight: Int) {    print("\(name) age = \(age), height = \(height)cm, weight = \(weight)kg")}personInfo("xiaoming", age: 18, height: 178, weight: 65)

以上是第一种默认参数名.

func personInfo(name: String, _ age: Int, _ height: Int, _ weight: Int) {    print("\(name) age = \(age), height = \(height)cm, weight = \(weight)kg")}personInfo("xiaoming", 18, 178, 65)

以上就是使用下标方法隐藏掉参数名, 但由于第一个参数名默认就是隐藏的, 所以我们这里的name就不需要使用下标.

func personInfo(personName name: String, personAge age: Int, personHeight height: Int, personWeight weight: Int) {    print("\(name) age = \(age), height = \(height)cm, weight = \(weight)kg")}personInfo(personName: "xiaoming", personAge: 18, personHeight: 178, personWeight: 65)

以上就是使用别名设置的参数名, 但别名只能在外部调用该函数时才能使用, 而在函数内部是使用不了的.


好了, 这次就讲到这里, 下次继续

0 0
原创粉丝点击