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 的參數也是可變的,可以把多個參數放在一個數組中
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 }
上面的閉包 沒搞明白。。。
新聞熱點
疑難解答