1. 程式人生 > >Xcode專案中不同Swift版本導致的問題

Xcode專案中不同Swift版本導致的問題

你會問同一個Xcode專案中還會用不同版本的Swift?

對!舉個栗子:2年前你寫了一個管理密碼的App,最近你覺得有必要再寫一個Today Widget外掛用來便捷顯示密碼。

之前的程式碼Swift版本是3.2(假設),而最新的Widget則使用4.0

為什麼不把3.2的程式碼升級到4.0呢?這是可以的,但是涉及到要改很多地方:

升級帶來許多問題

而且3.2和4.0也不是完全不相容,只是在某些地方新舊版本會有衝突,沒必要為了這一點相容性而老專案全部升級版本。

比如說對於NSMutableAttributedString的操作,4.0之後對於屬性名稱的引用方式和之前有不同,無法寫出3.2和4.0都能編譯通過的程式碼。

對於3.2和4.0都會引用到的程式碼片段,我們必須因”版”而異,用Swift的編譯巨集命令做程式碼隔離:

#if swift(>=4.0)
            attrString.addAttribute(.foregroundColor, value: UIColor.red, range: range)
            attrString.addAttribute(.backgroundColor, value: UIColor.green, range: range)
            attrString.addAttributes([.shadow:keywordShadow,.verticalGlyphForm
:0], range: range) #else attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range) attrString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.green, range: range) attrString.addAttributes([NSShadowAttributeName:keywordShadow,NSVerticalGlyphFormAttributeName:0
], range: range) #endif

以上程式碼在專案的公共組裡的String+ext.swift檔案中,該檔案會同時被App和Widget專案包含使用。

使用如上所示的程式碼隔離,或稱為選擇編譯使得全部專案順利編譯通過。