1. 程式人生 > >Swift學習-函式(六)

Swift學習-函式(六)

這章就以程式碼的方式記錄了,力求做到:簡潔、完整。

//帶引數 返回值的函式

        func sayHello(_ personName:String) ->String

        {

            let greeting = "Hello, " + personName + "!"

            return greeting

        }

        print(sayHello("feng"))

        //多個引數

        func halfOpenRangeLength(start:Int, end:Int

) ->Int

        {

            return end - start

        }

        print(halfOpenRangeLength(start: 1, end:10))//9

        //沒引數到函式

        func sayHelloWorld() ->String

        {

return"Hello, world"

        }

//沒有返回值的函式-其實是返回特殊值void(是一個空元組())

        func sayGoodBye(personName:String)

        {

            print("Goodbye,\(personName)")

        }

//通過元組返回多個值

        func minMax(_ array:[Int]) -> (min:Int, max:Int)

        {

            var currentMin = array[0]

            var currentMax = array[0]

//array[1..<array.cout]返回範圍內的值構成的新陣列

            for value in array[1

..<array.count]{

                if value < currentMin

                {

                    currentMin = value

                }else if value > currentMax

                {

                    currentMax = value

                }

            }

            return (currentMin, currentMax)

        }

        let bounds = minMax([8,-6,2,109,3,71])

        print("min is\(bounds.min) and max is\(bounds.max)")

//min is -6 and max is 109

//可選元組返回型別,(Int,Int)?與元組包含可選屬性如(Int?, Int?)不同。前者是整個元組是可選的

        func minMaxOptional(_ array:[Int]) -> (min:Int, max:Int)? {

            if array.isEmpty {return nil}

            var currentMin = array[0]

            var currentMax = array[0]

//array[1..<array.cout]返回範圍內的值構成的新陣列

            for value in array[1..<array.count]{

                if value < currentMin

                {

                    currentMin = value

                }else if value > currentMax

                {

                    currentMax = value

                }

            }

            return (currentMin, currentMax)

        }

        if let bounds = minMaxOptional([8,-8,2,110,3,71])

        {

            print("min is\(bounds.min) and max is\(bounds.max)")

        }

//min is -8 and max is 110

        //外部引數名

        func someFunction(to person:String, and anotherPerson:String)->String

        {

            return"Hello\(person) and\(anotherPerson)!"

        }

        print(someFunction(to:"feng", and:"liu"))//Hello feng and liu!

//   忽略第二個及後續的引數設定的引數名,用下劃線(_)代替

        func someFunction1(_ firstParameterName:Int,_ senondParameterName:Int)->Int

        {

            return firstParameterName + senondParameterName

        }

//呼叫不需要引數名

print(someFunction1(2,2))//4

// 帶預設引數的函式

        func someFunction2(_ parameterWithDefault:Int = 12)

        {

            print(parameterWithDefault)

        }

someFunction2() //12

someFunction2(5)//5

/*使用(...)來定義可變引數接受0個或多個值

         Double... 相當於 Double[]陣列

         函式最多有一個可變引數,為避免歧義一般寫在引數列表的最後

         如果函式有多個預設值,可變引數也放在引數列表最後

         */

        func arithmeticMean(_ numbers:Double...) ->Double

        {

            var total:Double = 0

            for number in numbers

            {

                total += number

            }

            return total / Double(numbers.count)

        }

        print(arithmeticMean(1,2,3,4,5))// 3.0

//函式預設引數為常量,不能更改值。

// 可變引數已經在swift4中不可用

        func alignRight( _ string:String, totalLength:Int, pad:Character)->String

        {

//用var宣告一個可變變數數(其生命週期只存在於函式體)

            var string = string

            let amountToPad = totalLength - string.count

            if amountToPad < 1

            {

                return string

            }

            let padString = String(pad)

            for _ in 1...amountToPad

            {

                    string = padString + string

            }

            return string

        }

        let originalString = "hello"

        let paddedString = alignRight(originalString, totalLength:10, pad: "-")

        print(paddedString)//-----hello

//inout 定義輸入輸出引數

        func swapTwoInts( a:inout Int,  b:inout Int)

        {

            let temporaryA = a

            a = b

            b = temporaryA

        }

        var someInt = 3

        var anotherInt = 100

//傳入引數是需要前面加"&",表示變數可以修改

        swapTwoInts(a: &someInt, b: &anotherInt)

        print("someInt:\(someInt),anotherInt:\(anotherInt)")//someInt:100,anotherInt:3

//函式型別(有函式引數型別和返回值型別組成)例如(Int,Int) -> Int

        func addTwoInts(a:Int,_ b:Int)->Int

        {

            return a + b

        }

        func multiplyTwoInts(a:Int,_ b:Int)->Int

        {

            return a * b

        }

        func operatorIns(a:Int,_ b:Int,_ c:Int)->Int

        {

            return a + b + c

        }

//函式賦值給變數

        var mathFunction:(Int,Int)->Int = addTwoInts

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

        mathFunction = multiplyTwoInts

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

//報錯 引數不一樣 mathFunction已經是(Int,Int) -> Int

//mathFunction = operatorIns

//函式型別被swift推測

        var anotherMathFunction = addTwoInts

        print("anotherResult:\(anotherMathFunction(5,10))")//anotherResult:15

//函式型別作為引數

        func printMathResult(_ mathFunction:(Int,Int)->Int,_ a:Int, _ b:Int)

        {

            print("Result:\(mathFunction(a,b))")

        }

printMathResult(addTwoInts,3,5)//Result: 8

//函式作為返回型別(“—>”後寫完整的函式型別(如(Int)-> (Int)))

        func stepForward(input:Int) ->Int

        {

            return input + 1

        }

        func stepBackward(input:Int) ->Int

        {

            return input - 1

        }

        //返回一個函式

        func chooseStepFunction(backward:Bool) -> (Int)->Int

        {

            return backward ?stepBackward :stepForward

        }

        /*巢狀函式

         把函式定義在函式體中稱為巢狀函式

         對外不可見,可別他們的封閉函式呼叫。

         封閉函式也可以返回他的一個巢狀函式

         */

        func chooseStepFunction1(backwards:Bool) -> (Int)->Int

        {

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

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

            return backwards ?stepBackward :stepForward

        }

        var currValue = -4

        let moveNearToZero = chooseStepFunction1(backwards: currValue > 0)

        while currValue != 0 {

            print("\(currValue)...")

            currValue = moveNearToZero(currValue)

        }

        print("Zero!")

        //-4...

        //-3...

        //-2...

        //-1...

        //Zero!