import UIKit
/// 尾随闭包
func someFuncThatTakesClosure(closure: () -> Void) {
}
/// 不使用尾随闭包
someFuncThatTakesClosure(closure: {
})
/// 使用尾随闭包
someFuncThatTakesClosure {
}
let names = [“eva”, “adon”]
/// 字符串排序
let reversedNames = names.sorted {$0 > $1}
let mapNames = names.map { $0 + “_like”}
/// 将Int类型数组[16,58,10]转换为包含对应String类型的值的数组[OneSix,FiveEight,FiveOneZero]
let digitNames = [0: “Zero”, 1: “One”, 2: “Two”, 3: “Three”,
4: “Four”, 5:“Five”, 6: “Six”, 7: “Seven”,
8: “Eight”, 9: “Nine”]
let nums = [16,58,10]
let strs = nums.map { (number) -> String in
var number = number
var output = “”
repeat {
output = digitNames[number%10]! + output
number /= 10
} while number > 0
return output
}
“===================================================”
let newStr = “Hello World”.filter { (chart) -> Bool in
return !chart.description.elementsEqual(“o”)
}
var dic: [String: Any] = [“name” : “xiaoming”, “age” : 12, “sex” : “man”]
let newDic = dic.mapValues { (item) -> String in
return “(item)”
}
“===================================================”
let fruits = [“Apple”, “Orange”, “Puple”]
let filterList = fruits.filter { (item) -> Bool in
return item.contains(“p”)
}
print(filterList)
“===================================================”
/// 1
let fruitReduce = fruits.reduce(“100”) { (result, item) -> String in
return result + “、” + item
}
print(fruitReduce)
/// 2
func appendString(str1: String, str2: String) -> String {
return str1 + “、” + str2
}
let newReduce = fruits.reduce(“10”, appendString(str1:str2:))
print(newReduce)
“===================================================”
二维数组 合并成一个 解包optional 过滤nil
let counts = [2, 3]
let array = counts.compactMap { (item) -> Int? in
return item + 1
}
print(array)
let newArray = counts.flatMap { count in
fruits.map { fruit in
return fruit + " (count)"
}
}
print(newArray)
“===================================================”