1. Swift Magic
<1> Swifter book ??????
<2> Advanced Swift book ??????
<3> WWDC Session & Sample Code ??
<4> CountDown to WWDC 60 Days ??????
<5> SwifterSwift ??????
<6> iina & Alamofire & Kingfisher ??
<7> SwiftNIO ??
Tag:
** == Array_Dict_Set_Range + Sequence_Collection + Optional + Struct_Class + Encoding_Decoding + Function + String + Error + Generics + Protocol + C Bridging
2. Counterpart
Quick shot: 每個部分會用很簡短的話來提示,幫助自己記憶。
<1> Swifter book note
Quick shot: 基本圍繞 ** 這十一主題展開,其中的知識點在 Advanced Swift 中有更加詳細的講解。Playground 很強大,值得探索。
1. Range - … & ..<
2. Protocol - mutating + Self + extension + optional protocol
3. Sequence - IteratorProtocol + ExpressibleByArray/StringLiteral + subscript + typealias + associatedtype + lazy + indirect & nested enum + OptionSet + enumerate
4. Function - tuple + @autoclosure && ?? + @escaping + func nesting + default param + 屬性觀察 + final + KeyPath & KVO + 尾遞歸 + 性能考慮
5. Optional - chaining + operator + pattern-match + ImplicitlyUnwrappedOptional + 多重 Optional + Optional Map + where & pattern-match + do { … } + 判等
6. Struct & Class - func-params + weak & unowned + value & reference Type + 閉包歧義
7. String - regex + String & NSString + CustomStringConvertible & CustomDebugStringConvertible + Log輸出 + 輸出格式化
8. Error - 錯誤和異常處理 + 斷言 + fatalError
9. Generics - 隨機數生成 + 泛型擴展
10. Encode & Decode - JSON & Codable
11. C & OC & iOS -
UnsafePointer + C 指針內存管理 + COpaquePointer & C convention + 調用 C 動態庫 + C 代碼調用 和 @asmname + Toll-Free Bridging & Unmanaged<T>
@objc & dynamic + type(of:) + is + 類型編碼 @encode + Associated Object
@UIApplicationMain + @autoreleasepool + GCD & asyncAfter + singleton + 類簇 + delegate + @synchronized + NSNull + 宏定義 define + @dynamic == @NSManaged
12. Playground - 延時運行 與 項目協作 與 可視化開發
13. Swift - nameSpacing + init + designated & convenience & required + init? + static & class + [protocol] & case typeValue(type) + AnyClass & meta type & .self + dynamic Type + reflection & mirror + selector + dynamic call instance method + Swift 命令行工具 + 屬性訪問控制 + 兼容性 + @testable + 條件編譯 + 編譯標記
14. Other - 代碼組織和 Framework + 安全的資源組織方式 + 文檔注釋 + 溢出 32 64 + 哈希
<2> Advanced Swift note 1...5 & 6...
Quick shot: 一些語言的描述,措辭和文筆都非常值得學習。FIFOQueue & List & SortDescriptor & Regex 都是非常好的模板例子。源碼和 proposal 是核心呀。
介紹
<1> Swift 是什么樣的語言,與其他語言的相似之處,定義了值,變量,引用,常量。
<2> 為了避免引用的淺復制,引入了“寫時復制”這種高效的深復制技術。
<3> 閉包、柯里化函數、靜態派發、動態派發、重寫、重載、多態的定義。
<4> Swift API 設計準則Array_Dict_Set_Range
<1> Array 與 NSArray 的不同,Array 的基本操作。Array 的變形( Map、Filter、Reduce、flatMap、forEach) 與 ArraySlice
<2> Dict 的操作。Hashable 的要求。自動滿足Equatable 和Hashable
<3> Set (無序contains + 不重復) 與基本操作。IndexSet(范圍列表) 與CharacterSet(字符子集)。
<4> Range(..<) & ClosedRange(…)。CountableRange & CountableClosedRange。RangeExpressionSequence_Collection
<1> Sequence 的實現依賴于 Iterator。自定義 PrefixSequence,就默認具有 Sequence 的各種便利方法。
<2> 基于函數的 AnySequence + sequence(first/state:next:)
<3> SubSequence 及相關操作 + 鏈表(基于此可以實現 LRU)
<4> Collection + FIFOQueue: Collection + 遵守的最小條件
<5> Iterator + SubSequence + IndexDistance + Indices
<6> index + 自定義集合索引(WordsIndex & Words : Collection ) + Slice
<7> BidirectionalCollection + RandomAccessCollection + MutableCollection + RangeReplaceableCollectionOptional
<1> Optional chaining + ?? + Optional map/flatMap(與 if let 與 chaining) + Sequence flatMap
<2> 可選值判等 + fatalError & assert & precondition
<3> 隱式解包可選值Struct_Class
<1> 兩者不同點。mutating 與 inout
<2> 寫時復制及實現及陷阱(字典訪問與下標訪問)
<3> weak & unownedEncoding_Decoding
<1> Encodable & Decodable + 自動遵循 & 編解碼過程
<2> Encoder & KeyedContainer & UnkeyedContainer & SingleValueContainer
<3> 編譯器生成的代碼 - CodingKeys: CodingKey + encode(to:) + init(from:)
<4> 手動遵守協議 - 自定義 Coding Keys & 自定義 encode(to:) 和 init(from:)
<5> 他人的代碼 & 類 & 枚舉 滿足 CodableFunction
<1> SortDescriptor 實現 - 泛型 & Comparable & ComparisonResult & combine & <||> & 可選值
<2> merge 函數進化 + 函數作為代理
<3> willSet & didSet 與 KVO + lazy
<4> 下標(泛型) + 鍵路徑(SortDescriptor)(可寫鍵路徑(雙向綁定) + 鍵路徑層級)
<5> @autoclosure + @escapingString
<1> Unicode + unicodeScalars
<2> String + Character + : BidirectionalCollection, RangeReplaceableCollection
<3> String.Index 操作 + subString
<4> StringProtocol
<5> 編碼單元視圖 - unicodeScalars,utf16 和 utf8 + String 與Foundation API
<6> 文本輸出流 & TextOutputStream/able
<7> 字符串性能 - 幻影 (phantom) 類型Error
<1> Result 類型 + do/catch & throws
<2> rethrows + defer + try?Generics
<1> 自由函數的重載 + 運算符的重載 + 泛型約束重載(最小條件抽象) + 閉包對行為進行參數化(閉包判等)
<2>集合泛型 - (泛型)二分查找 + 集合隨機排列
<3> 泛型 - 代碼設計 + 共通功能 + 泛型數據類型
<4> 泛型的工作方式 + 特化 + 全模塊優化Protocol
<1> 接口抽象 + 關聯類型 + extension + 類型約束 & 獨立的類型
<2> protocol 與 繼承 + 協議方法的動/靜態派發
<3> 類型抹消 - 簡單方法 與 標準庫通過類繼承把類型隱藏在子類
<4> 不透明/類存在容器 + 目擊表
<5> 泛型參數 比 協議類型高效得多C Bridging
<1> C 導入 Swift + 封裝
<2> managed & unsafe & buffer & raw & mutable
<3> 指針 - Unsafe[Mutable]Pointer & Unsafe[Mutable]RawPointer & OpaquePointer & Unsafe[Mutable]BufferPointer & Unsafe[Mutable]RawBufferPointer
<4> MemoryLayout.size/stride + @convention(c)
<5> qsort_r - 類型安全 和 泛型接口 封裝
<3> WWDC Session & Sample Code
Quick shot:
Protocol and Value Type
Optimizing Swift Performance WWDC 2015 - 409
UITableView SingleCodePath - 基于 Lucid Dreams 及 IGListKit,Swift 實現的 UITableView 封裝。
<4> CountDown to WWDC 60 Days
Quick shot: 都是一些有時有用的 tips,像是 @dynamicMemberLookup 關鍵字和 debug 時的一些調試方法值得記錄。
<5> SwifterSwift
Quick shot:
- 在回顧的時候發現一個問題,如果想要實現的 extension 在最小條件的話,就需要熟悉一般性的 protocol 的基本操作。所以,有空的時候列舉一下。
- 加上一些時間復雜度低和靈活運用 protocol 內固有的屬性。
- 在未看源碼的前,拓展一些 protocol
guard startIndex..<endIndex ~= index else { return }
<T: Comparable>
KeyPath<Element, T?>
Element: Hashable
Element: Equatable
@discardableResult
mutating func removeDuplicates() -> [Element] {
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
return self
}
BidirectionalCollection - index(before:)
BinaryFloatingPoint
StringProtocol
RandomAccessCollection
RangeReplaceableCollection
<6> iina & Alamofire & Kingfisher
Quick shot: 已經過了一遍,等待精讀
<7> SwiftNIO
Quick shot: 已經過了一遍,等待精讀
3. Tricks
<1> Protocol
CustomStringConvertible & CustomDebugStringConvertible
Equatable & Hashable
Best practice for value types is to make them Equatable and Hashable
CaseIterable
enum PickerComponent: Int, CaseIterable {
case transitionType
case duration
}
PickerComponent.allCases.count
RangeReplaceableCollection
ExpressibleByDictionaryLiteral
ExpressibleByArrayLiteral
Sequence
Collection
<2> convenience Method
zip
let words = ["one", "two", "three", "four"]
let naturalNumbers = 1...Int.max
let zipped = Array(zip(words, naturalNumbers))
// zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
uniquingKeysWith
let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
let firstValues = Dictionary(pairsWithDuplicateKeys,
uniquingKeysWith: { (first, _) in first })
// ["b": 2, "a": 1]
let lastValues = Dictionary(pairsWithDuplicateKeys,
uniquingKeysWith: { (_, last) in last })
// ["b": 4, "a": 3]
isDisjoint
let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
print(employees.isDisjoint(with: visitors))
// Prints "true"
<3>
狀態機
public enum State {
case initialized, resumed, suspended, cancelled
/// Determines whether `self` can be transitioned to `state`.
func canTransitionTo(_ state: State) -> Bool {
switch (self, state) {
case (.initialized, _): return true
case (_, .initialized), (.cancelled, _): return false
case (.resumed, .cancelled), (.suspended, .cancelled),
(.resumed, .suspended), (.suspended, .resumed): return true
case (.suspended, .suspended), (.resumed, .resumed): return false
}
}
}
optional switch
private func allCallbacks() -> [Element] {
switch (self.firstCallback, self.furtherCallbacks) {
case (.none, _):
return []
case (.some(let onlyCallback), .none):
return [onlyCallback]
case (.some(let first), .some(let others)):
return [first] + others
}
}
context 確定,可以用 . 調用類方法
public static let defaultAcceptLanguage: HTTPHeader = {
.acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded)
}()
初始化用尾隨 closure 簡潔
public typealias Transformer = (CIImage) -> CIImage?
public struct Filter {
let transform: Transformer
public init(transform: @escaping Transformer) {
self.transform = transform
}
}
let f = Filter { input in }
defer
lock.lock(); defer { lock.unlock() }
outputStream.open()
defer { outputStream.close() }
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
let filteredItems = r.items?.filter { item in
!(r.latestItems?.contains(where: { item.id == $0.id }) ?? false)
}
let i = items.map { (url, str) -> (URL?, String?) in
var string: String? = str
if let index = string?.firstIndex(of: " ") {
string?.replaceSubrange(index...index, with: "\n")
return (url, string)
}
return (url, str)
}
???
func op() {
requestData()
}
func requestData() {
print(#function)
}
func requestData(append: Bool = false) {
print(#function + "append")
}