為了適配 iOS 10,無奈之下只能把 Swift 專案升級到 Xcode 8,沒想到一入 3.0 深似海,從此幸福是路人。於是邊摸索邊修改,趕在節前完成程式碼遷移。節後忙完手頭工作,整理思路,把這段 Swift 3 遷移的心得分享給大家。廢話不多說,直接進入主題。




在左側選擇頁中挑選要轉換的程式碼,左邊是 Swift 3.0 版本,右側是 Swift 2.2 版本,確認後點擊 Save。

"Use Legacy Swift Language Version" (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

在 Pod 的設定檔中,把 Use Legacy Swift Language Version 選為 YES,錯誤即消除。路徑:Pods → TARGETS → 指定框架 → Build Settings → Use Legacy Swift Language Version。


解決方式:PROJECT → Build Settings → Build Active Architecture only → 設為 YES。

其他問題後續再收集整理。
由於 3.0 的大幅改動,各家主流框架都已推出新版本,例如 Alamofire 4.0.0、SnapKit 3.0.0、Kingfisher 3.1.0,SwiftyJSON 也更新了專供 Swift 3 的分支,因此需要更新框架以便使用。

pod 'SnapKit', '~> 3.0.0' pod 'SwiftyJSON', :git => 'https://github.com/acegreen/SwiftyJSON.git', :branch => 'swift3' pod 'Alamofire','~> 4.0.0' pod 'Kingfisher','~> 3.1.0'
過程中可能會遇到以下問題:

看到兩百多個框架錯誤時確實凌亂。明明都已是 3.0 語法,為何還報錯?問題不在框架本身,而與本機安裝的 CocoaPods 環境有關。
解決方案:更新到最新環境 cocoapods 1.1.0.rc.2。
sudo gem install cocoapods --pre
可參考 SnapKit 官方 issues:https://github.com/SnapKit/SnapKit/issues/300

Alamofire/Source/ServerTrustPolicy.swift:243:41: Use of unresolved identifier 'kSecTrustResultInvalid'
參考 Alamofire 官方 issues:https://github.com/Alamofire/Alamofire/issues/1541
解決方案:更新到最新的 Alamofire 框架。
pod 'Alamofire','~> 4.0.0'
還可能遇到的問題:
[!] Unable to satisfy the following requirements: - `Alamofire (~> 4.0.0)` required by `Podfile` Specs satisfying the `Alamofire (~> 4.0.0)` dependency were found, but they required a higher minimum deployment target.
當時的解法:Alamofire 4.0.0 最低要求系統版本 9.0,即使把系統升到 9.0 仍無法安裝。暫時沒找到有效解法,唯一方案是重新立項,先集成框架,再把轉換好的程式碼遷移到新專案中。
10 月 24 日更新解法:需在 Podfile 中明確指定最低系統 9.0,即 platform :ios, '9.0'。參考 Alamofire 官方 issues:https://github.com/Alamofire/Alamofire/issues/1639

前面提到,有些個別問題一直解不開,與其死磕,不如用最簡潔的方法——重新建立工程。
先把新工程集成好支援 Swift 3.0 的最新第三方框架,測試程式能否跑通,再把先前轉換好的程式碼一個分類一個分類地遷移進來。
至於手動拖入的第三方依賴庫、應用跳轉等,按照先前集成好的照搬或重新集成即可。
1. 官方已提供文檔與轉變說明。Apple Swift 3.0 官方文檔:The Swift Programming Language (Swift 3)

2. Apple Swift 3.0 官方演進說明:apple/swift-evolution/releases/swift-3_0.md

主要是廢除了一些 API、簡化了程式碼書寫,例如移除 OC 中的 NS 類前綴、去除 C 語言風格等等。
3. 國外 raywenderlich 的 Swift 3.0 遷移介紹:https://www.raywenderlich.com/135655/whats-new-swift-3

對 Swift 3 的書寫方式仍需進一步加強。雖說與先前的寫法只有輕微差異,整體變得更簡潔、更嚴謹,但只要稍不注意還是會冒出莫名其妙的報錯。展望 Swift 4,就讓暴風雨來得更猛烈些吧。歡迎討論、批評、指正。