filter函数适用于过滤操作, 方法体是一个返回值为bool的闭包
map 函数适用于遍历的操作之后的一个映射
reduce 函数适用于对原来的数据进行给定一个初始值, 进行修改, 并返回修改后的值
Array
extension Array {
/**
* transform是一个函数参数(closure参数), 参数是Element, 返回值是T
**/
func myMap<T>(_ transform: (Element) -> T) -> [T] {
//transform保存的是 $0 * $0
print(Element.self)
var tmp:[T] = []
tmp.reserveCapacity(count)
for value in self {
//执行transform函数, 也就是执行$0 * $0, $0是一个参数, value就是实参, 传入value后, 执行$0 * $0
//然后把$0 * $0的结果添加到tmp里面
tmp.append(transform(value))
}
return tmp
}
func myFilter(_ predicate:(Element) -> Bool) -> [Element] {
var tmp:[Element] = []
for value in self where predicate(value) {
tmp.append(value)
}
return tmp
}
func myReduce<T>(_ initial: T, _ next: (T, Element) -> T) -> T {
print(T.self)
print(Element.self)
print(next)
var tmp = initial
for value in self {
tmp = next(tmp, value)
}
return tmp
}
}
声明一个数组
var fiveInts = [1, 2, 3, 4, 5]
求平方
print(fiveInts.myMap{$0 * $0})
//[1, 4, 9, 16, 25]
过滤
print(fiveInts.myFilter{ $0 % 2 == 0 })
//[2, 4]
求和
print(fiveInts.myReduce(0, +))
//15
Dictionary
extension Dictionary {
mutating func merge<S:Sequence>(_ sequence: S)
where S.Iterator.Element == (key: Key, value: Value) {
sequence.forEach{ self[$0] = $1 }
}
init<S:Sequence>(_ sequence: S)
where S.Iterator.Element == (key: Key, value: Value) {
self = [:]
self.merge(sequence)
}
}
var dic:[String:String] = ["a":"1"]
let dic1:[String:String] = ["b":"2"]
//合并两个字典
dic.merge(dic1)
//从一个字典中生成一个字典
let dic3 = Dictionary(dic)
dic3
数组元素去重
extension Sequence where Iterator.Element : Hashable {
func unique() -> [Iterator.Element] {
var tmp: Set<Iterator.Element> = []
return filter{
if tmp.contains($0) {
return false
}else {
tmp.insert($0)
return true
}
}
}
}
[1, 1, 3, 5, 3, 4].unique()
自定义数据当做key
/**
* 字典的key值都是可哈西的(key值最好使用值类型即struct), 要想把自定义的数据类型作为key, 该数据结构必须是可哈西的
* 可哈西需要实现Hashable协议
* 两个相等的对象的哈希值必须是相同的, 实现Equatable来解决这个问题
*/
struct Account {
var type: Int
var name: String
}
extension Account: Hashable {
var hashValue: Int {
//a^b = b^a, 此处有风险
return type.hashValue ^ name.hashValue
}
}
extension Account: Equatable {
//必须定义成静态方法
//两个参数表示等号两边的比较对象
static func == (lhs: Account, rhs: Account) -> Bool {
return lhs.type == rhs.type &&
lhs.name == rhs.name
}
}
var data:[Account:Int]?