Swift - 自定义函数规则说明

1,无返回值的函数
1
2
3
func test(name: String ){
}

2,返回一个返回值
) ->Bool{
return true
}

3,返回由多个值组成的复合返回值
3
4
5
) -> ( Int , var position = 1
visible = false
return (position,visible)
}

4,可变形参:可以接受0个或者任意数量的输入参数
5
6
7
test(numbers: ...) -> count: = 0
for number in numbers{
count += number
}
count
}

5,在Swift函数中,参数认是常量。如果要改变参数的值,就需要在定义函数的时候加上关键字var。(外部的参数任然不会被修改
7
8
9
10
11
12
age = 22
add(age)
//无法编译
add(age: ) {
age += 1
}
//可以编译
add( age: ) {
age += 1
}

6,如果想要同时改变函数内外的参数值,可以利用inout关键字,同时调用函数的时候给参数加上前缀“&”
add(&age)
print (age) //23
inout ){
}

7,可以使用函数类型的参数
10
additive(a: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,b: a + b
}
//函数类型的参数
printAdditiveResult(addFun: ( ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,a: ){
( "Result:\(addFun(a,b))" )
}
printAdditiveResult(additive,a: 5,b: 7)

8,也可以使用函数类型的返回值
12
13
14
15
16
17
18
//定义个自增函数
increase(input: {
input + 1
}
//定义个自减函数
reduce(input: {
input - 1
}
//定义一个返回函数类型的函数
chooseFunction(backwards: {
backwards ? reduce : increase
}
//测试
let aFun = chooseFunction(3>2)
(aFun(3)) //2

原文出自: www.hangge.com 转载请保留原文链接 http://www.hangge.com/blog/cache/detail_517.html

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...