Swift 中的 Functions

BrittanyRud 8年前發布 | 5K 次閱讀 Swift Apple Swift開發

LearniOS

Swift

Functions

1、雖然(Example1)中的函數沒有返回值類型,但是嚴格的講,該方法( greet(person:) )還是返回了一個值,即使沒有定義返回值。如果函數沒有定義返回值的話,它默認會返回一個類型為Void的具體值。會返回一個空的元祖( 寫做() )。

Example1 :

func greet(person: String) {
    print("Hello, \(person)!")
}

2、返回值可以被忽略。

返回值可以被忽略,但是一個聲明了返回值的函數必須有返回值。如果你聲明的函數有返回值,而你的函數體內并沒有返回值的話,編譯器會報錯。

3、 (Int, Int)? 和 (Int?, Int?) 是不同的。一個可選的元祖類型,并不是意味著它包含的每個值都是可選類型。

Example2 :

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}

4、如果你不想每個參數都寫一個參數標簽,你可以使用'_'來代替參數標簽(eg:Example3)。

Example3 :

func someFunction(_ firstParameterName : Int, secondParameterName: Int) {
    // _代表第一個參數
}
someFunction(1, secondParameterName: 2)

5、通過在參數類型后面給參數添加一個值,你可以定義任何參數的默認值。如果參數被設置默認值,在調用該方法的時候你可以忽略該參數(Example4)。

Example4 :

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {

} someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault 為 6 someFunction(parameterWithoutDefault: 4) // parameterWithDefault 為 12</code></pre>

6、一個可變參數可以接受0個或者多個指定類型的參數。 你使用可變參數來指定在調用函數時,參數可以傳遞不同數量的輸入值. 在參數類型后面添加三個點(...)來表明它為可變參數(Example5)。

  • 一個函數最多有一個可變參數。
  • 函數參數默認為常量。

Example5 :

func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// return 3
arithmeticMean(3, 8.25, 18.75)
// returns 10.0

7、輸入輸出參數不能有默認值,并且可變參數不能標記為inout。你只能將變量聲明為in-out參數。

8、In-out參數和函數的返回值是不一樣的。下面的例子并沒有定義返回值,但是它仍然能修改someInt和anotherInt的值。In-out可以影響函數體外的參數值(Example6)。

Example6 :

func swapTwoInts( a: inout Int,  b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) print("someInt is now (someInt), and anotherInt is now (anotherInt)") //someInt = 107 anotherInt = 3</code></pre>

9、函數解讀

Example7 :

func printHelloWorld() {
    print("hello, world")
}

上面函數的類型為 () -> Void ,或者是一個沒有參數,返回值為Void的函數。

Example8 :

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
var mathFunction: (Int, Int) -> Int = addTwoInts

定義一個名字為mathFunction的變量,它的類型為:有兩個Int類型的參數,并且返回值為Int的函數。該變量指向addTwoInts函數。

10 函數當參數

Example9 :

func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)

11、內嵌函數

嵌套函數默認情況下從外部隱藏,但仍然可以由其封閉函數調用和使用。封閉函數還可以返回其一個嵌套函數,以允許嵌套函數在另一個作用域中使用(Example9)。

Example10 :

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 現在等同于stepForward函數,因為(currentValue > 0)為false
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")

 

來自:https://github.com/fengzhihao123/LearniOS/blob/master/Swift/functions.md

 

 本文由用戶 BrittanyRud 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!