A Swift Tour(3)

來源:互聯網
上載者:User

Functions and Closures

使用func來聲明函數,通過括弧參數列表的方式來調用函數,用 --> 來分割函數的傳回型別,參數名和類型,例如:

func greet(name: String, day: String) -> String {        return "Hello \(name), today is \(day)."    }greet("Bob",  day: "Tuesday")  //這是swift文檔中的調用方法,但是我在xcode6中編寫的時候總報錯,所以採用了下面的方式greet("Bob",  day: "Tuesday") //使用這種方式不會錯誤

使用一個元組一個函數可以返回多個值

func getGasPrices() -> (Double,Double,Double)    {        return (3.97,3.59,3.79)    }getGasPrices()

上面的方法我不知道用什麼來接收返回的值,請高手支招

func 的參數也是可變的,可以把多個參數放在一個數組中

func sumOf(sumbers:Int...) -> Int    {        var sum = 0        for number in sumbers        {            sum += number        }        return sum    }println(sumOf())    //return 0println(sumOf(42, 597, 12))   //return 651

函數可以嵌套,嵌套的函數可以訪問在外部函數中聲明的變數,你可以使用嵌套函數來解決複雜的邏輯:

    func returnFifteen() -> Int    {        var y = 10        func add()        {            y += 5        }        add()        return y;    }        println(returnFifteen()) //return 15

函數是一個 first-class 類型,這意味著函數的傳回值可以是另一個函數:

func makeIncrementer() -> (Int -> Int) {        func addOne(number: Int) -> Int {            return 1 + number        }        return addOne    }var increment = makeIncrementer()increment(7)//上面的代碼一直報錯,不知道什麼原因//錯誤:Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254//如果哪位高手知道,請指教

一個函數可以作為另一個函數作為其參數

func hasAnyMatches(list: Int[],condition: Int-> Bool) -> Bool    {        for item in list        {            if(condition(item))            {                return true            }        }        return false    }        func lessThanTen(number: Int) -> Bool    {        return number < 10;    }        var numbers = [20,19,7,12]        let temp = hasAnyMatches(numbers, lessThanTen)        println(temp)//這個和上面一樣的錯,也有事我的xcode6 有問題

你可以通過{}來些一個閉包

numbers.map({    (number: Int) -> Int in    let result = 3 * number    return result    })

這個閉包有的時候可以寫的更加簡潔,比如你知道他的傳回型別或者其他的

numbers.map({ number in 3 * number })
sort([1, 5, 3, 12, 2]) { $0 > $1 }

上面的閉包 沒搞明白。。。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.