swift基础之函数

原创
2021/04/12 11:43
阅读数 26

默认参数

func greet(_ person: String = "zhang san", _ hometown: String = "bei jing") -> String {
    return "Hello \(person)! Glad you could visit from \(hometown)"
}

print(greet())
//Hello zhang san! Glad you could visit from bei jing

不定参数个数

//不定参数个数
func sum(_ nums: Int...) -> Int {
    var ret = 0
    for n in nums {
        ret += n
    }
    return ret
}

print(sum(1,2,3))
//6
print(sum(1,2,3,4,5))
//15

函数内改变函数外定义的参数值

//函数内改变函数外定义的参数值
func swap(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
}

var a = 1
var b = 2
swap(&a, &b)
print(a)
//2
print(b)
//1

函数类型变量

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

var addFunc: (Int, Int) -> Int = add
print(addFunc(1, 2))
//3

函数类型参数

func printResult(_ f: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(f(a, b))")
}
printResult(add, 1,2)
//Result: 3

函数类型作为返回值

func forward(_ input: Int) -> Int {
    return input + 1
}
func backward(_ input: Int) -> Int {
    return input - 1
}
func step(isBack: Bool) -> (Int) -> Int {
    return isBack ? backward : forward
}

//记数倒数到0
var currValue = 3
let moveNearerToZero = step(isBack: currValue > 0)
print("Counting to zero:")
while currValue != 0 {
    print("\(currValue)...")
    currValue = moveNearerToZero(currValue)
}
print("zero!")
/*
 Counting to zero:
 3...
 2...
 1...
 zero!
 */

内嵌函数

func chooseStepFunc(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int {
        return input + 1
    }
    func stepBackward(input: Int) -> Int {
        return input - 1
    }
    return backward ? stepBackward : stepForward
}

print("Counting to zero:")
var cVal = -4
let toZero = chooseStepFunc(backward: cVal > 0)
while cVal != 0 {
    print("\(cVal)...")
    cVal = toZero(cVal)
}
print("zero!")
/*
 Counting to zero:
 -4...
 -3...
 -2...
 -1...
 zero!
 */
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部