函數(shù)也可以作為一個類型(引用類型)
func add (_ a: Int, _ b: Int) -> Int
{
return a + b
}
let anotherAdd = add // let anotherAdd: (Int, Int) -> Int = add 等同于诫咱, 這里的 add 函數(shù)作為一個類型
anotherAdd(2, 4)
`_` 表示忽略參數(shù)名 `= 99999, =1000` 表示默認(rèn)值
func add(_ num1: Int = 99999, _ num2: Int = 1000) -> Int
{
return num1 + num2
}
add(2, 3)
add(2)
// 這里調(diào)用 是因為有默認(rèn)參數(shù)
add()
// 這里的 `and` 是外部參數(shù)名
func add(_ num1: Int = 99999, _ num2: Int = 1000, and num3: Int) -> Int
{
return num1 + num2 + num3
}
add(and: 3)
add(2, 3, and: 4)
變長的參數(shù)類型
一個函數(shù)最多只有一個變長的參數(shù)類型
func mean (_ numbers: Int ...) -> Int
{
var sumValue = 0
for num in numbers {
sumValue += num
}
return sumValue
}
// 這里可以傳入多個值
mean(2, 4, 6, 8, 10)
交換2個數(shù)的值
inout
代表傳入地址, 加上這個關(guān)鍵字后可以改變出入的參數(shù)值
func swapValues (_ num1: inout Int, _ num2: inout Int)
{
let temp: Int = num1
num1 = num2
num2 = temp
}
var X: Int = 100, Y: Int = 200
swapValues(&X, &Y)
X
Y
參數(shù)是函數(shù)
func calculate(scores: inout [Int] , changeValue: (Int) -> Int) {
for (index, score) in scores.enumerated() {
scores[index] = changeValue(score);
}
print(scores)
}
func changeValue(value: Int) -> Int {
return value * 10
}
var score: [Int] = [1, 2, 3, 4, 5]
// 調(diào)用
calculate(scores: &score, changeValue: changeValue)
執(zhí)行結(jié)果:[10, 20, 30, 40, 50]
高階函數(shù)
高階函數(shù)map、flatMap罕扎、filter辐棒、reduce
map: 可以對數(shù)組中的每一個元素做一次處理\
let scores = [40, 89, 100, 78, 97, 50]
func isPass (score: Int) -> Bool
{
return score < 60
}
scores.map(isPass) // [true, false, false, false, false]
filer:過濾狭归,可以對數(shù)組中的元素按照某種規(guī)則進行一次過濾
let scores = [40, 89, 100, 78, 97, 50]
func isPass (score: Int) -> Bool
{
return score < 60
}
scores.filter(isPass) // [40, 50]
reduce:計算梗醇,可以對數(shù)組的元素進行計算
func joint (string: String, num: Int) -> String
{
return string + String(num) + ","
}
scores.reduce("", joint) // 40,89,100,78,97,50,