Swift - 自定义函数规则说明

来源:互联网 发布:微信公众平台源码下载 编辑:程序博客网 时间:2024/05/22 15:37
//: Playground - noun: a place where people can playimport UIKitvar str = "Hello, playground"// 【自定义函数规则说明】//  1.无返回值的函数func test(name: String){}// 2.返回一个返回值func test2(name: String) -> Bool {    return true}// 3.返回由多个值组合成的复合返回值func test3(name: String) -> (Int,Bool) {    let position = 1    let visiable = false    return (position,visiable)}// 4.可变形参: 可以接受0个或者任意数量的输入参数func test4(numbers: Int...) -> Int {    var count: Int = 0    for number in numbers {        count += number    }    return count}// 6.如果想要同时改变函数内外的参数值,可以利用inout关键字,同时调用函数的时候给参数加上前缀"&"var age = 22func add(inout age: Int){    age += 1}add(&age)print(age) //23// 7.可以使用函数类型的参数func additive(a: Int, b:Int) -> Int {    return a + b}// 函数类型的参数func printAdditiveResult(addFun: (Int,Int) -> Int, a:Int, b:Int) {    print("Result:\(addFun(a,b))")}printAdditiveResult(additive, a: 5, b: 7)// 8.也可以使用函数类型的返回值// 定义自增函数func increase(input:Int) -> Int {    return input + 1}// 定义自减函数func reduce(input:Int) -> Int {    return input - 1}// 定义一个返回函数类型的函数func chooseFunction(backwards:Bool) -> (Int) -> Int {    return backwards ? reduce : increase}// 测试let aFun = chooseFunction(3 > 2)print(aFun(3)) // 2
0 0
原创粉丝点击