Swift学习笔记第四篇(函数)

函数

在 Swift 中,每个函数都有一种类型,包括函数的参数值类型和返回值类型。你可以把函数类型当做任何其他普通变量类型一样处理,这样就可以更简单地把函数当做别的函数的参数,也可以从其他函数中返回函数。函数的定义可以写在在其他函数定义中,这样可以在嵌套函数范围内实现功能封装。

单参数

/// 单参数
///
/// - Parameter personName: 参数1
/// - Returns: 返回类型
func sayHello(personName:String) -> String
{
    let greeting = "Hellow," + personName + "!"
    return greeting
}

print(sayHello(personName: "MKJ"))

多参数

/// 多参数
///
/// - Parameters:
///   - num1: 参数1
///   - num2: 参数2
/// - Returns: 返回类型
func delataTwoNumber(num1:Int, num2:Int) -> Int
{
    return num1 - num2
}

print(delataTwoNumber(num1: 10, num2: 1))

let funcD = delataTwoNumber
funcD(11,111)

无参数

/// 无参数
///
/// - Returns: 返回类型
func sayHelloWorld() -> String {
    return "hello, world"
}
print(sayHelloWorld())

func printSingleSlogan(slogan:String){
    print("woca,"+slogan + "!")
}

printSingleSlogan(slogan: "CJJ")

默认参数

/// 默认参数名
///
/// - Parameters:
///   - string1: 参数1
///   - string2: 参数2
///   - joiner: 参数3
/// - Returns: 返回值
func join(string1:String,string2:String,joiner:String = "+") -> String
{
    return string1 + joiner + string2
}

print(join(string1: "我", string2: "你")) // "我+你\n"
print(join(string1: "他", string2: "她", joiner: "0")) // "他0她\n"

可变参数

一个可变参数(variadic parameter)可以接受一个或多个值。函数调用时,你可以用可变参数来传入不确定数量的输入参数。通过在变量类型名后面加入(…)的方式来定义可变参数。
传入可变参数的值在函数体内当做这个类型的一个数组

/// 可变参数
///
/// - Parameter numers: 参数数组
/// - Returns: 返回值
func total(numers:Double...) -> Double
{
    var totalD  = 0.0
    for numer in numers {
        totalD += numer
    }
    return totalD / Double(numers.count)
}



print("total is " + "\(total(numers: 2,10,21))")

输入输出参数(inout)

变量参数,正如上面所述,仅仅能在函数体内被更改。如果你想要一个函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数(In-Out Parameters)。

定义一个输入输出参数时,在参数定义前加 inout 关键字。一个输入输出参数有传入函数的值,这个值被函数修改,然后被传出函数,替换原来的值。

你只能将变量作为输入输出参数。你不能传入常量或者字面量(literal value),因为这些量是不能被修改的。当传入的参数作为输入输出参数时,需要在参数前加&符,表示这个值可以被函数修改。

注意: 输入输出参数不能有默认值,而且可变参数不能用 inout 标记。如果你用 inout 标记一个参数,这个参数不能被 var 或者 let 标记。

/// 输入输出参数
///
/// - Parameters:
///   - a: 外部变量地址a
///   - b: 外部变量地址b
func swapTwoInts( a: inout Int, b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var someInt = 3
var anotherInt = 107
//swapTwoInts(a: &someInt, b: &anotherInt)
swapTwoInts(a: &someInt, b: &anotherInt)
print("\(someInt)" + "\(anotherInt)")

函数类型使用

(参数1,参数2,参数3) -> (返回值1,返回值2)
可以理解为传入三个需要类型的参数,返回一个有两个指定类型的元祖

/// 使用函数类型
///
/// - Parameters:
///   - a: 参数1
///   - b: 参数2
/// - Returns: 返回值
func add(a:Int,b:Int)->Int
{
    return a+b
}

func mutiby(a:Int,b:Int)->Int
{
    return a*b
}
// 指定函数类型
var mathFunction :(Int,Int) -> Int = add

print("Result:\(mathFunction(2,3))")

mathFunction = mutiby

print("Result:\(mathFunction(3,5))")

// 自动推断函数类型
let mathFunc = add
print("Result:\(mathFunc(2,5))")

我们申明变量指向函数的时候可以手动指定函数的类型,如果你不指定,swift会自动进行类型推断

函数类型作为参数

/// 函数作为参数
///
/// - Parameters:
///   - a: <#a description#>
///   - b: <#b description#>
/// - Returns: <#return value description#>
func mathAdd(a:Int,b:Int) -> Int{
    return a+b
}

func printMathResult(mathFunc:(Int,Int)->Int,a:Int  ,b:Int){
    print("Result-->\(mathFunc(a,b))")
}

printMathResult(mathFunc: mathAdd, a: 3, b: 14)

printMathResult 函数的作用就是输出另一个合适类型的数学函数的调用结果。它不关心传入函数是如何实现的,它只关心这个传入的函数类型是正确的。这使得 printMathResult 可以以一种类型安全(type-safe)的方式来保证传入函数的调用是正确的。

函数作为类型返回

你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头(->)后写一个完整的函数类型。

/// 函数作为返回值
///
/// - Parameter number: <#number description#>
/// - Returns: <#return value description#>
func goForward(number:Int)->Int{
    return number + 1
}

func goBackward(number:Int)-> Int{
    return number - 1
}

func chooseStepFunction(chooseFlag:Bool) -> (Int)->Int{

    return chooseFlag ? goBackward : goForward
}

var countingNumber = 3
let moveFunc = chooseStepFunction(chooseFlag:  countingNumber > 0)

while countingNumber != 0 {
    print(String(countingNumber))
    countingNumber = moveFunc(countingNumber)
}
print("0!")

/// 3 2 1 0!

嵌套函数

你所见到的所有函数都叫全局函数(global functions),它们定义在全局域中。你也可以把函数定义在别的函数体中,称作嵌套函数(nested functions)。

/// 嵌套函数
///
/// - Parameter chooseFlag: <#chooseFlag description#>
/// - Returns: <#return value description#>
func nestChooseStepFunction(chooseFlag:Bool) -> (Int)->Int{
    func stepF(num:Int)->Int{return num + 1}
    func stepB(num:Int)->Int{return num - 1}
    return chooseFlag ? stepF : stepB
}

var countingNum = -5
let resultFunc = nestChooseStepFunction(chooseFlag: countingNum < 0)

while countingNum < 0 {
    print("\(countingNum)" + "!")
    countingNum = resultFunc(countingNum)
}
print("0!")
/*
 -5!
 -4!
 -3!
 -2!
 -1!
 0!
 */

你可能感兴趣的:(Swift学习笔记)