Swift 学习笔记 —— 函数

前端之家收集整理的这篇文章主要介绍了Swift 学习笔记 —— 函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Swift 中函数的基本表达式
// func + 函数名+(参数) + ->返回参数的类型

func sum(#number1:Int,#number2:Int)->Int{
      return number1 + number2
}

Swift中函数的默认参数值
// 你可以在函数体中为每个参数定义默认值。当默认值被定义后,调用这个函数时可以忽略这个参数。
// 带有默认参数值的形参,swift 会自动给它生成一个跟形参名相同的外部参数名

func join2 (#string:String,#toString:String,joiner:String = " 123 ")->String{
    return  string  + joiner + toString
}
// 函数调用
join2(string: "hellow",toString: "word" )  // 输出记结果为 "hellow 123 word" 

 join2(string: "hellow",toString: "word",joiner: "+") // 输出结果为 "hellow+word” 

// 注意 : 在 swift 中”_”的 作用就是用来忽略一切东西的

func join2 (#string:String,toString:String,_ joiner:String = " 123 ")->String{
    return  string  + joiner + toString
}
join2(string: "hellow",toString:"word","+")  // 输出结果为 "hellow+word” 

Swift 函数中的常量参数和变量参数

 // 常量参数,参数无法在函数内部中更改值
func test(num:Int) 相当于 func test(let num:Int) 参数 num 是不可变的 // 变量参数,在参数前面加上 Var 即可改变参数的值
func test(var #num:Int){
    num = 10
}

Swift 函数中的输入输出参数
如果想要在函数内部更改外界参数的值,在函数的参数前面加关键字 inout

func swapTowInts(inout num1:Int,inout num2:Int){
    let temp = num1
    num1 = num2;
    num2 = temp;
}
var num1 = 20
var num2 = 10
// 函数调用
swapTowInts(&num1,&num2) // 注意:参数前面必须加&


//以下写法是错误
swapTowInts(&10,&20) // 不能传入常量或者字面量(比如10)作为参数值(因为他们都不可改)

Swift 函数中的将函数作为参数使用

func sum2(num1:Int,num2:Int)->Int{
    return num1 + num2
}

func printMathResult(mathFunction: (Int,Int) -> Int,a: Int,b: Int) -> Void {
    println("Result: \(mathFunction(a,b))")
}

// 函数调用
printMathResult(sum2,10,20)   // 输出结果为 Result: 30

这里的mathFunction: (Int,Int) -> Int函数成为了一个内部参数,而跟这个参数对应的外部参数为 sum


Swift 函数中的 函数作为返回类型

func backSum(input:Int) ->Int{
    return input + 1
}

func backRelase(input:Int) ->Int{
    return input - 1
}
func judgeBack(#backwords:Bool) ->(Int) ->Int{  // 它的返回类型是 (Int) -> Int 的函数
    return backwords ? backRelase :  backSum
}

var currentValue = 3

// 函数调用
var result = judgeBack(backwords: currentValue > 2)

因为3>2是 ture,所以现在 result 指向了 backRelase 函数

println("Counting to zero:")
while currentValue != 0{
    println("\(currentValue)")
    currentValue = result(currentValue) // currentValue 等于不断调用backRelase函数直到为0
}
println("zero")

Swift 函数中的嵌套函数(Nested Functions)
意思就是让内部参数不被外界访问,当做他们封闭函数(enclosing function)来调用

以下是更改judgeBack函数代码

func judgeBack(#backwords:Bool) ->(input:Int) ->Int{
   func backSum(input:Int) ->Int{return input + 1}
   func backRelase(input:Int) ->Int {return input - 1}
    return backwords ? backRelase :  backSum
}
var currentValue = 3
var result = judgeBack(backwords: currentValue > 2)
println("Counting to zero:")
while currentValue != 0{
    println("\(currentValue)")
    currentValue = result(input: currentValue) // currentValue 等于不断调用backRelase函数直到为0
}
println("zero")
原文链接:https://www.f2er.com/swift/326269.html

猜你在找的Swift相关文章