//: Playground - noun: a place where people can play
import UIKit
var 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 = 22
func 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
Swift - 自定义函数规则说明
最新推荐文章于 2025-08-06 10:13:08 发布
1932

被折叠的 条评论
为什么被折叠?



