Swift關鍵字 Open Source + Growing Ecosystem
Language refinements and additions
Access Control
"private": 作用域變為可在"extension"中訪問
Composing Classes and Protocols
"class"和"protocol"可以組合起來使用
protocol Shakeable {
func shake()
}
extension UIButton: Shakeable { /* … */ }
extension UISlider: Shakeable { /* … */ }
func shakeEm(controls: [UIControl & Shakeable]) {
for control in controls where control.state.isEnabled {
control.shake()
}
}
Reference
Section What's New in Foundation
- SE-0161 Smart KeyPaths: Better Key-Value Coding for Swift
- SE-0166 Swift Archival & Serialization
- SE-0167 Swift Encoders
Source compatibility
Swift 4 largely source-compatible with Swift 3
這次總算是向前兼容Swfit 3了: Swift 3 和 Swift 4可以共存在同一個項目中
可以對Target單獨設定Swift的版本,但是對我們這種只有單獨Target的產品而言,還是只能支持一種啊?
Tools and performance
Build Improvements
新的編譯系統提供更快的編譯速度,特別是對于大的項目
"Precompiled Bridging Headers": 在OC/Swift混合代碼中橋接頭文件會很慢,使用預編譯可以有效的加快編譯時間
"Shared Build for Coverage Testing": XCode9不再需要重新編譯
"Indexing While Building": 避免"Background indexing"的重復工作,在編譯的過程中直接更新"index"
Predictable Performance
"COW Existential Buffers": Copy-On-Write,只有在修改時才拷貝,避免昂貴的堆Heap
分配消耗
"Faster Generic Code": 在使用泛型Generic
時,用Stack
取代Heap
進行棧分配
Smaller Binaries
Swift 4 會自動移除未被使用的代碼
"Limited @objec Inference"
- Swift 3會自動給繼承自
NSObject
的非私有的類和成員自動加上@objc
,而Swift 4只有在確定需要的時候才被加入 - 對于不可再OC中表達的代碼自動報錯
- "Migrator"不能夠確認所有需要加
@objc
的方法,但是對于可以確定的,會通過"Warning"的形式報"deprecated"提醒,然后我們再手動的添加 - 遷移完成后可將"Swift 3 @objec Inference"設置改為"Default"
"Symbol Size"
- Swift symbols在symbol table極少使用,在新的配置中自動刪除
Standard library
Swift Strings
Swift: A Character is a grapheme
- Swift 4中對字符處理更快:拉丁文、漢字符、片假名
- Swift 3 一個
strings
"包含"一個字符集合 - Swift 4 一個
strings
"就是"一個字符集合
"Simpler one-sided Slicing Syntax"
- 簡化范圍運算符為單向
"Substrings"
- 區分
Substrings
和Strings
為不同的類型,避免在僅有Substrings
存在的情況下占用過多內存 -
Substrings
可以當做Strings
來使用,享有相同的方法
"Multi-line String Literals"
- 優化了多行字符串的書寫
- Swift 3 需要使用換行符
- Swift 4 直接書寫,編譯器會自動去除格式"\t\t"
New Generics Features
where closure in the associatetype
- 限定
asociatetype
Generic Subscript
-
Subscript
可以使用泛型,包括Return Type
和Subscript Type
Exclusive access to memory
Non-Exclusive Access to Memory
無法控制混亂的訪問,以及可能導致的性能問題
Enforcing Exclusive Access to Memory
Swift 4只允許同時讀操作
Run-time Enforcement
- 編譯階段不一定知道是否引用同一個實體,可以通過運行時報錯
- Global variables
- Properties of classes
- Local variables captured in escaping closures
Multi-threaded Enforcement
- 默認的審查無法在多線程情況下工作
- Default enforcement only catches single-threaded bugs
- Thread Sanitizer catches multi-threaded bugs (其它的演講)
設置
- Compile-time enforcement: 默認打開
- Run-time enforcement: 默認關閉