//----------------? 0.3 函數(shù)? ---------------
import UIKit
1.Swift 函數(shù)基本格式? func 名稱 (參數(shù)名:參數(shù)類型,參數(shù)名:參數(shù)類型)->返回值
func greet(_ person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
var str = greet( "Bob", day: "Tuesday") //調(diào)用函數(shù)
print(str)
2.Swift默認(rèn)函數(shù)參數(shù)名為參數(shù)的標(biāo)簽。在參數(shù)名稱之前可以自定義參數(shù)標(biāo)簽,或者 **在參數(shù)名前面寫 _ 就可以不使用參數(shù)標(biāo)簽。**
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")//可以看到 person 前面有 _? 所以在調(diào)用的時(shí)候 person 可以省略
3.使用元組創(chuàng)建一個(gè)復(fù)合值,例如,從函數(shù)返回多個(gè)值。元組的元素可以通過名稱或數(shù)字來引用。
//eg: 找出數(shù)組中中的最大最小值,求和
func calculateStatistics(scores:[Int]) -> (min:Int,max:Int,sum:Int){
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
}else{
min = score
}
sum += score
}
return (min,max,sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])//statistics即為元組
print("min = \(statistics.min), max = \(statistics.max), sum = \(statistics.sum)")//包裝成字符串形式后用\()輸出值(??)
//關(guān)于元組小 eg
let st = (frist:123,1234,1234)
print("frist == \(st.frist) ,\(st.1),\(st.2)")
//函數(shù)可以嵌套。嵌套函數(shù)可以訪問在外部函數(shù)中聲明的變量。
func returnFifteen() -> Int {
var y = 10
func add()-> (Int,Int) {
y += 5
return (y,2)
}
return add().0
}
print(returnFifteen())
4.函數(shù)可以返回另一個(gè)函數(shù)作為返回值進(jìn)行傳遞
func makeIncrementer() -> ((Int) -> Int) {//括號(hào)中的(Int) -> Int 代表此函數(shù)返回的是一個(gè)函數(shù)
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()//同時(shí)你也可以把一個(gè)函數(shù)當(dāng)做變量去使用!!!!
increment(7)
5.函數(shù)可以作為參數(shù)傳入函數(shù)中處理
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {//(Int) -> Bool表示此函數(shù)需要傳入一個(gè)函數(shù)作為參數(shù)
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]
hasAnyMatches(list: numbers, condition: lessThanTen)
6.閉包初體驗(yàn)
//函數(shù)實(shí)際上是一個(gè)特殊的閉包情況:稍后可以調(diào)用的代碼塊。閉包中的代碼可以訪問在創(chuàng)建關(guān)閉的范圍內(nèi)可用的變量和函數(shù),即使它們在執(zhí)行時(shí)封閉在不同的范圍內(nèi) - 您看到已經(jīng)有嵌套函數(shù)的示例。您可以使用大括號(hào)({})的周圍代碼編寫一個(gè)沒有名稱的閉包。使用in分離參數(shù)和從包體返回類型。({ in })
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
//您有幾個(gè)選項(xiàng)可以更簡潔地寫入閉包。當(dāng)閉包類型已知時(shí),例如代理的回調(diào),您可以省略其參數(shù)的類型,其返回類型或兩者。單個(gè)語句閉包隱式地返回它們唯一的語句的值。
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
//您可以通過數(shù)字而不是名稱來引用參數(shù) - 這種方法在非常短的關(guān)閉中特別有用。作為函數(shù)的最后一個(gè)參數(shù)傳遞的閉包可以在括號(hào)后立即顯示。當(dāng)閉包是函數(shù)的唯一參數(shù)時(shí),可以完全省略括號(hào)。
let sortedNumbers = numbers.sorted { $0 > $1 }
print(sortedNumbers)