Swift Section Four(函数与闭包) 2014-10-23 swift swift 函数与闭包 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165//: Playground - noun: a place where people can playimport UIKit//swift 第四课 函数与闭包//1.函数的用法func greet(name: String, day: String) ->String {return "Hello \(name), today is \(day)"}greet("Bob","Tuesday")//2.多返回值的函数func calculateStatistics(scores: [Int]) ->(min: Int, max: Int, sum: Int){var min = scores[0]var max = scores[0]var sum = 0for score in scores{if score > max {max = score}else if score < min{min = score}sum += score}return (min, max, sum)}let statistics = calculateStatistics([5, 3, 100, 3, 9])print(statistics.sum)print(statistics.2)//3.不限参数个数的函数func sumOf(numbers: Int...) -> Int {var sum = 0for number in numbers{sum += number}return sum}sumOf()sumOf(42, 597, 12)//4.嵌套函数func returnFifteen() -> Int{var y = 10func add(){y += 5}add()return y}returnFifteen()//5.函数可以作为函数的返回值func makeIncrementer() -> (Int -> Int){func addOne(number: Int) -> Int {return 1 + number}return addOne}var increment = makeIncrementer()increment(7)//5.函数也可以作为函数的参数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, 5, 12]hasAnyMatches(numbers, lessThanTen)//6.闭包的使用//首先介绍一下map方法的定义:返回一个数组,这个数组内的元素是原数组经过闭包函数计算返回的值numbers.map({(number: Int) -> Int inlet result = 3 * numberreturn result})//简写方式let mappedNumbers = numbers.map({number in 3 * number})print(mappedNumbers)//利用闭包排序let sortedNumbers = numbers.sorted {$0 > $1}print(sortedNumbers) 源代码请前往我的github Newer Swift Section Five(对象与类) Older Swift Section Three(分支和循环)