Swift2.3適配Swift3.0
升級Xcode8.0Beta版,看著公司Swift版本的專案200多個報紅,那種酸爽也就蘋果能給。慢慢改吧!改的東西很多,但基本都不難,記錄幾個花費較長時間的Bug。
NO.1
【報錯】“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.
【解決方法】設定 Build Settings —-> Use Legacy Swift Language Version —-> YES/NO,改為NO或者YES
NO.2
【問題】控制檯打印出大量無用的資訊。
【解決方法】在 Environment Variables
中新增欄位 name:OS_ACTIVITY_MODE
,value:disable
NO.3
【問題】整個專案能編譯通過,但在執行時啟動頁出現後就黑屏
【解決方法】問題在於,AppDelegate中didFinishLaunchingWithOptions
這個方法沒有走。雖然是利用系統提供的修復,自動從Swift2.3修復到Swift3,但修復完的這個方法也還是不對的。
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { }
修改為
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { }
NO.4
【報錯】“ambiguous referenc to member datask(with: completionhandler:)”
【解決方法】這個是在URLSessionDataTask
中遇到的,屬於型別不明確的報錯。
修改前的程式碼:
let task: URLSessionDataTask = session.dataTask(with: request) { (data, resp, err) in }
修改後的程式碼:
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, resp, err) in }
// 由於request是NSMutableURLRequest型別,在request 後面添加了 as URLRequest
NO.5
【報錯】”Cannot pass immutable value of type ‘NSDate?’ as inout argument”
【解決方法】var beginDate: NSDate? = NSDate()
修改前的程式碼:
var beginDate: Date?
var endDate: Date?
let calendar: Calendar = Calendar.current
let ok: Bool = calendar.range(of: Calendar.Unit.month, start: &beginDate, interval: &interval, for: newDate as Date)
修改後的程式碼:
var beginDate: NSDate? = NSDate()
var endDate: NSDate? = NSDate()
let calendar: Calendar = Calendar.current
let ok: Bool = calendar.range(of: Calendar.Unit.month, start: &beginDate, interval: &interval, for: newDate as Date)
NO.6
【警告】”Expression of type “UIViewController?” is unused”.
【解決】Swift3之前,每個方法都有一個預設的可以廢棄的結果。
相關解決例項:
// 例一:
_ = navigationController?.popViewController(animated: true)
// 例二:
t_principal.mas_makeConstraints { (make) in
_ = make?.top.mas_equalTo()(0)
_ = make?.left.mas_equalTo()(20)
_ = make?.height.mas_equalTo()(self.frame.size.height / 3 - 1)
_ = make?.width.mas_equalTo()(self.frame.size.width / 2 - 30)
}