swift3 函数方法
发布时间:2020-12-14 06:22:07 所属栏目:百科 来源:网络整理
导读:定义函数: 形式:func 函数名(参数名1:类型,参数名2:类型,…) - 返回结果的类型 {执行语句} 调用:var 变量名称 = 函数名(变量1,变量2,…) 1.有参数有返回值 func add (x: Int,y: Int) - Int { return x + y} var z = add( x : 3 , y : 4 ) // 7 //可以给某
定义函数:
1.有参数有返回值func add(x: Int,y: Int) -> Int {
return x + y
}
var z = add(x: 3,y: 4) //7
//可以给某个参数以默认值
func add2(x :Int,increment : Int = 2) -> Int {
return x + increment
}
add2(x: 3) //5
add2(x: 3,increment: 3) //6
2.无参数无返回值无参数无返回值 :一般用于执行一系列操作,不需要结果. func welcome() {
print("欢迎")
print("学习")
}
welcome()
3.多返回值(使用元组)func maxMin() -> (Int,Int) {
let Range1 = Range(1..<8);
return (Range1.lowerBound,Range1.upperBound)
}
maxMin() //(.0 1,.1 8)
maxMin().0 //1
maxMin().1 //8
4.参数类型为函数类型函数类型:包含参数和返回类型的简写形式,可以像普通变量那样使用,一般用于函数式编程. func calculate(x: Int,y: Int,method: (Int,Int)->Int ) -> Int { return method(x,y) }
func add(x: Int,y: Int) -> Int { return x + y }
func multiply(x: Int,y: Int) -> Int { return x * y }
calculate(x: 3,y: 4,method: add) //7
calculate(x: 5,y: 6,method: multiply) //30
5.参数为可变类型默认情况下方法的参数是let值,也就是不可改变的。 func test( i:inout Int){
i += 1
print(i)
}
var x = 10
test(i: &x) //11
print(x) //"11n"
参考自 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |