【swift-總結】函數

來源:互聯網
上載者:User

標籤:

swift的函數在swift2中的使用改變了不少
/***param: personName 參數*returns: String為傳回值*/func sayHello(personName: String) -> String {    return "Hello " + personName;}
/*swift2中函數的調用必須要使用標籤或者別名,沒有別名第一個標籤不帶*/func add(a: Int, b: Int) -> Int {    return a + b;}print(add(1, b:2));
/*如果使用了別名,函數調用的時候必須使用別名*/func add(num1 a: Int, b: Int) -> Int {    return a + b;}print(add(num1: 1, b:2));
返回多個值
/*返回多個值,也就是返回一個元組*/var nums = [1, 2, 3, 4, 5]func minMax(array: [Int]) -> (min: Int, max: Int) {    var minNum = array[0];    var maxNum = array[0];    for num in array {        if num < minNum {            minNum = num        } else if num > maxNum {            maxNum = num        }    }    return (minNum, maxNum);}print(minMax(nums).max);print(minMax(nums).min);
返回可選的元組
var nums = [1, 2, 3, 4, 5]func minMax(array: [Int]) -> (min: Int, max: Int)? {    if array.isEmpty {        return nil;    }    var minNum = array[0];    var maxNum = array[0];    for num in array {        if num < minNum {            minNum = num        } else if num > maxNum {            maxNum = num        }    }    return (minNum, maxNum);}print(minMax(nums)!.max);print(minMax(nums)!.min);
預設參數
func numFun(num: Int = 22) {    print(num);}numFun();//輸出22
可變參數
func numAdd(nums: Int...) {    var sum = 0;    for num in nums {        sum += num;    }    print(sum);}numAdd(1, 2, 3);
不用標籤調用函數的情況
func addNum(_ a:Int, _ b: Int) {   a + b;}addNum(a, b);
變數參數

函數參數預設為常量,函數內部不能改變參數的值
要想在函數內部改變參數的值,就要使用變數作為參數

func swapNum(var a:Int, var b: Int) {    var temp = a;    a = b;    b = temp;}
in-out參數

函數預設是使用拷貝傳遞函數的
使用in-out修飾參數表示參數是使用指標傳遞函數

func swapNum(inout a:Int, inout b: Int) {    let temp = a;    a = b;    b = temp;}var a = 1;var b = 2;swapNum(&a, b: &b);print("a is \(a), b is \(b)");
函數類型
func add(a: Int, b: Int) -> Int {    return a + b;}print(add( 1, b:2));/*聲明一個變數,後面是函數類型*/var addNum: (Int, Int) -> Int = add;print(addNum(2, 3));
函數類型作為參數
func result(numFun: (Int, Int) -> Int, a: Int, b: Int) {    print(numFun(a, b));}result(addNum, a: 6, b: 7);
函數類型作為傳回值
/*返回一個函數*/func chooseFunc() -> (Int) -> Int {}
嵌套函數
func addNum(a: Int, b: Int) {    func printNum() {        print(22);    }    printNum();    print(a + b);}var a = 1;var b = 3;addNum(a, b:b);

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【swift-總結】函數

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.