Swift 4 Cheat Sheet Pro
@(编程笔记)[Swift]
这个是在 Swift 4 Cheat Sheet Advanced 的基础上再次进阶的小抄,内容并没有多高端,只是 Cheat Sheet Advanced 更多是常用语法,而这里搜集的是一些很有用但是又需要一定基础的语法。如果滥用,既容易降低代码可读性也容易出错。
Protocols
https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
Conditionally Conforming to a Protocol
extension Array: TextRepresentable where Element: TextRepresentable {
var textualDescription: String {
let itemsAsText = self.map { $0.textualDescription }
return "[" + itemsAsText.joined(separator: ", ") + "]"
}
}
let myDice = [d6, d12]
print(myDice.textualDescription)
// Prints "[A 6-sided dice, A 12-sided dice]"
Generics
func swapTwoValues(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
func someFunction(someT: T, someU: U) {
// function body goes here
}
https://docs.swift.org/swift-book/LanguageGuide/Generics.html
Advanced Operators
https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
Bitwise NOT Operator
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // equals 11110000
Bitwise AND Operator
let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits // equals 00111100
Bitwise OR Operator
let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits // equals 11111110
Bitwise XOR Operator
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // equals 00010001
Bitwise Left and Right Shift Operators
Shifting Behavior for Unsigned Integers
let shiftBits: UInt8 = 4 // 00000100 in binary
shiftBits << 1 // 00001000
shiftBits << 2 // 00010000
shiftBits << 5 // 10000000
shiftBits << 6 // 00000000
shiftBits >> 2 // 00000001
Map, FlatMap, compactMap, Filter, Reduce And Sort
Map
let values = [2.0,4.0,5.0,7.0]
let squares2 = values.map({
(value: Double) -> Double in
return value * value
})
// [4.0, 16.0, 25.0, 49.0]
FlatMap
使用 flatMap
函数替代 map
函数的原因在于前者能够忽略可选值为 nil 的情况。例如 flatMap([0,nil,1,2,nil])
的结果是 [0,1,2]
。
其实整个 flatMap 方法可以拆解成两步:
第一步像 map 方法那样,对元素进行某种规则的转换。
第二步,执行 flatten 方法,将数组中的元素一一取出来,组成一个新数组。
http://www.infoq.com/cn/articles/swift-brain-gym-map-and-flatmap
let arr = [[1, 2, 3], [6, 5, 4]]
let brr = arr.flatMap {
$0
}
// brr = [1, 2, 3, 6, 5, 4]
// 等价于:
let arr = [[1, 2, 3], [6, 5, 4]]
let crr = Array(arr.map{ $0 }.flatten())
// crr = [1, 2, 3, 6, 5, 4]
compactMap
Swift 4.1 引入。用以替代flatMap的特定实现Sequence.flatMap(_: (Element) -> U?) -> [U]
。
https://github.com/apple/swift-evolution/blob/master/proposals/0187-introduce-filtermap.md
'flatMap' is deprecated: Please use compactMap(:) for the case where closure returns an optional value. Use 'compactMap(:)' instead.
let names: [String?] = ["Tom", nil, "Peter", nil, "Harry"]
let valid = names.compactMap { $0 }
// ["Tom", "Peter", "Harry"]
let words = ["53", "nine", "hello","0"]
let values = words.compactMap { Int($0) }
// [53, 0]
Filter
let digits = [1, 4, 5, 10, 15]
let even = digits.filter { (number) -> Bool in
return number % 2 == 0
}
// [4, 10]
Reduce
https://swift.gg/2015/12/10/reduce-all-the-things/
Reduce 的基础思想是将一个序列转换为一个不同类型的数据,期间通过一个累加器(Accumulator)来持续记录递增状态。为了实现这个方法,我们会向 reduce 方法中传入一个用于处理序列中每个元素的结合(Combinator)闭包 / 函数 / 方法。
求和范例:
// 初始值 initial 为 0,每次遍历数组元素,执行 + 操作
[0, 1, 2, 3, 4].reduce(0, combine: +)
// 10
反转数组:
// $0 指累加器(accumulator),$1 指遍历数组得到的一个元素
[1, 2, 3, 4, 5].reduce([Int](), combine: { [$1] + $0 })
// 5, 4, 3, 2, 1
划分(Partition)处理:
// 为元组定义个别名,此外 Acc 也是闭包传入的 accumulator 的类型
typealias Acc = (l: [Int], r: [Int])
func partition(lst: [Int], criteria: (Int) -> Bool) -> Acc {
return lst.reduce((l: [Int](), r: [Int]()), combine: { (ac: Acc, o: Int) -> Acc in
if criteria(o) {
return (l: ac.l + [o], r: ac.r)
} else {
return (r: ac.r + [o], l: ac.l)
}
})
}
partition([1, 2, 3, 4, 5, 6, 7, 8, 9], criteria: { $0 % 2 == 0 })
//: ([2, 4, 6, 8], [1, 3, 5, 7, 9])
Sort
-
sorted()
回传排序结果,不影响数组内容。 -
sort()
回传排序结果,并将结果存回数组。
var numbers = [2, 4, 6, 8, 1, 3, 5, 7]
numbers.sorted(<) //return: [1, 2, 3, 4, 5, 6, 7, 8]
numbers //return: [2, 4, 6, 8, 1, 3, 5, 7]
numbers.sort(>)
numbers //return: [8, 7, 6, 5, 4, 3, 2, 1]
struct MyCustomStruct {
var someSortableField: String
}
var customArray = [
MyCustomStruct(someSortableField: "Jemima"),
MyCustomStruct(someSortableField: "Peter"),
MyCustomStruct(someSortableField: "David"),
MyCustomStruct(someSortableField: "Kelly"),
MyCustomStruct(someSortableField: "Isabella")
]
customArray.sort {
$0.someSortableField < $1.someSortableField
}