函数的定义与调用
func sayHello(personName: String) -> String { let greeting = "Hello," + personName + "!" return greeting } print(sayHello("Anna")) // prints "Hello,Anna!" print(sayHello("Brian")) // prints "Hello,Brian!"
可变参数
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 numbers arithmeticmean(3,8,19) // returns 10.0,which is the arithmetic mean of these three numbers
常量参数和变量参数
输入输出参数
func swapTwoInts(inout a: Int,inout b: Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt,b: &anotherInt) print("someInt is Now \(someInt),and anotherInt is Now \(anotherInt)") // prints "someInt is Now 107,and anotherInt is Now 3”
嵌套函数
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 = -4 let moveNearerToZero = chooseStepFunction(currentValue > 0) // moveNearerToZero Now refers to the nested stepForward() function while currentValue != 0 { print("\(currentValue)... ") currentValue = moveNearerToZero(currentValue) } print("zero!") // -4... // -3... // -2... // -1... // zero!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。