Swift4 基礎部分:Functions

本文是學習《The Swift Programming Language》整理的相關隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點。

系列文章:

Defining and Calling Functions

這一節主要講解Swift中的函數,Swift中函數的定義直接看一下官方例子一目了然。

例子:

func greet(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting
}
print(greet(person: "Arnold"));

執行結果:

Hello, Arnold!

多返回值函數(Functions with Multiple Return Values)

You can use a tuple type as the return type for a function to return multiple values as part of one compound return 
value.
  • SWift中的函數的返回值可以是一個元組類型數據。

例子:

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

if let (min,max) = minMax(array: [2,5,3,1,6]){
    print("min:\(min),max:\(max)");
}

執行結果:

min:1,max:6

注意可選型的使用,保證安全性

指定參數標簽(Specifying Argument Labels)

You write an argument label before the parameter 
name,separated by a space
  • Swift的函數中可以在參數名的前面以空格隔開加入參數標簽

例子:

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}

print(greet(person: "Bill", from: "Cupertino")) 

執行結果:

Hello Bill!  Glad you could visit from Cupertino.

默認參數值(Default Parameter Values)

You can define a default value for any parameter in a 
function by assigning a value to the parameter after that 
parameter’s type. If a default value is defined, you can 
omit that parameter when calling the function.
  • 函數中的參數如果需要默認的值可以直接寫在參數之后
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    print("parameterWithoutDefault \(parameterWithoutDefault),parameterWithDefault \(parameterWithDefault)");
}

someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6);
someFunction(parameterWithoutDefault: 4);

執行結果:

parameterWithoutDefault 3,parameterWithDefault 6
parameterWithoutDefault 4,parameterWithDefault 12

可變參數(Variadic Parameters)

A variadic parameter accepts zero or more values of a 
specified type. You use a variadic parameter to specify 
that the parameter can be passed a varying number of input 
values when the function is called. Write variadic 
parameters by inserting three period characters (...) 
after the parameter’s type name.
  • Swift中引入了可變參數的概念,參數后加入...即可表示,該類型的數據可以傳入0或者多個

例子:

func calculate(_ numbers: Double...) -> (Double){
    var sum :Double = 0.0;
    for var number in numbers{
        sum += number;
    }
    return sum;
}

print("sum:\(calculate(1,2,3,4,5))");

執行結果:

sum:15.0

In-Out Parameters

Function parameters are constants by default. Trying to 
change the value of a function parameter from within the 
body of that function results in a compile-time error. 
This means that you can’t change the value of a parameter 
by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the 
function call has ended, define that parameter as an in-
out parameter instead.
  • 函數的參數默認都是常量定義的,如果需要函數內部更改參數的值需要將參數用inout修飾

例子:

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var a:Int = 1;
var b:Int = 2;
swap(&a, &b);
print("a:\(a),b:\(b)");

執行結果:

a:2,b:1

函數作為參數(Function Types as Parameter Types)

You can use a function type such as (Int, Int) -> Int as a 
parameter type for another function. This enables you to 
leave some aspects of a function’s implementation for the 
function’s caller to provide when the function is called. 

例子:

func add(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum + secondNum;
}

func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum - secondNum;
}

func calculate(_ calculateFunction:(Int,Int) -> Int,_ firstNum:Int,_ secondNum:Int) -> Int{
    return calculateFunction(firstNum,secondNum);
}

print("add \(calculate(add,3,2))");
print("minus \(calculate(minus,3,2))");

執行結果:

add 5
minus 1

函數作為返回值(Function Types as Return Types)

You can use a function type as the return type of another 
function. You do this by writing a complete function type 
immediately after the return arrow (->) of the returning 
function.

例子:

func add(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum + secondNum;
}

func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum - secondNum;
}

func calculator(_ isAdd:Bool) -> (Int,Int) -> Int{
    return isAdd ? add : minus;
}

var invokeCalculator = calculator(true);
print("add \(invokeCalculator(1,2))");
invokeCalculator = calculator(false);
print("minus \(invokeCalculator(3,2))");

執行結果:

add 3
minus 1

內嵌函數(Nested Functions)

直接看一個例子,把上一個例子中的addFunction,minusFunction放到calculator中即可。

例子:

func calculator(_ isAdd:Bool) -> (Int,Int) -> Int{
    
    func add(_ firstNum:Int,_ secondNum:Int) -> Int{
        return firstNum + secondNum;
    }
    
    func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
        return firstNum - secondNum;
    }
    
    return isAdd ? addFunction : minusFunction;
}

var invokeCalculator = calculator(true);
print("add \(invokeCalculator(1,2))");
invokeCalculator = calculator(false);
print("minus \(invokeCalculator(3,2))");

執行結果:

add 3
minus 1
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,241評論 4 61
  • 轉載自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子閱讀 8,724評論 0 36
  • 版本記錄 前言 我是swift2.0的時候開始接觸的,記得那時候還不是很穩定,公司的項目也都是用oc做的,并不對s...
    刀客傳奇閱讀 1,191評論 0 0
  • 2014.3.15.@桉木的文 剛看到一篇很久以前寫的文章,看了很好笑,但心也有點酸。 有人說:暗戀是戀愛中最美好...
    呂桉木閱讀 841評論 2 5
  • 我喜歡不帶目的地游走于這人世間,這樣遇到的人碰到的景都將是驚喜。我喜歡驚喜。失去驚喜我就不知道如何活。
    Messier42閱讀 301評論 0 1