swift 快速奔跑的兔几 本节的内容是:函数(函树?嘿嘿嘿^.^)
发布时间:2020-12-14 01:41:36 所属栏目:百科 来源:网络整理
导读:通常,函数以参数为输入时是按值传送的,输出返回的也是值。但是,使用inout关键字定义了参数,那就可以按引用传递参数,直接改变这个变量中存储的值。例如: import UIKitfunc swapValues(inout firstValue:Int,inout secondValue: Int){ let temp = firstV
通常,函数以参数为输入时是按值传送的,输出返回的也是值。但是,使用inout关键字定义了参数,那就可以按引用传递参数,直接改变这个变量中存储的值。例如: import UIKit
func swapValues(inout firstValue:Int,inout secondValue: Int){
let temp = firstValue
firstValue = secondValue
secondValue = temp
}
var swap1 = 2
var swap2 = 3
swapValues(&swap1,secondValue: &swap2)
swap1//3
swap2//2
swift中,函数可以用作变量,也就是说,在需要的情况下,函数可以返回一个函数——那么更神奇的就是,可以用函数创建新的函数,并在自己的代码中使用这个函数,栗子如下: import UIKit
func createAdder(numberToAdd: Int) -> (Int) -> Int {
func adder(number: Int) -> Int {
return number + numberToAdd
}
return adder
}
var addTwo = createAdder(2)
addTwo(5)//7
函数还可以捕获一个值,并多次使用它。 import UIKit
func createIncrementor(incrementAmount: Int) -> () -> Int{
var amount = 0
func incrementor() ->Int{
amount += incrementAmount
return amount
}
return incrementor
}
var incrementByTen = createIncrementor(10)
incrementByTen()//10
incrementByTen()//20
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |