升級 Swift 4.2 教程

如果喜歡這篇文章巍棱,歡迎點贊或者點個關(guān)注:[我的微博](http://weibo.com/devlcd) 梆造,以后發(fā)布文章,會第一時間在微博通知

## 依賴庫

> 如果你看的時候項目依賴的所有庫都支持了 Swift 4.2 請忽略這部分內(nèi)容,直接從下節(jié)開始

因為現(xiàn)在Xcode正式版還沒放出來睛蛛,第三方庫也都沒有支持 Swift 4.2 夭坪,第一步就是先通過修改podfile讓不支持 Swift 4.2 的第三方庫在4.1下編譯文判,等到所有依賴的第三方庫都支持 Swift 4.2 之后,再把 podfile 改回去

```

swift_41_pod_targets = ['SnapKit','MonkeyKing','RxCocoa', ...]

post_install do | installer |

? ? installer.pods_project.targets.each do |target|

? ? ? ? if swift_41_pod_targets.include?(target.name)

? ? ? ? ? ? target.build_configurations.each do |config|

? ? ? ? ? ? ? ? config.build_settings['SWIFT_VERSION'] = '4.1'

? ? ? ? ? ? end

? ? ? ? end

? ? end

end

```

## 修改工程配置

在 Build Setting 中搜索 `Swift Language Version` 將 Swift 版本號改為 Swift 4.2

注:如果項目包含多個 Target 的室梅,記得把所有的 target 按以上步驟戏仓,將 Swift 版本改為 Swift 4.2

## 系統(tǒng)代理方法變更

每次升級 Swift 最坑的就是系統(tǒng)代理方法變更,而自己沒有發(fā)現(xiàn)亡鼠,修改完語法之后以為沒問題赏殃,結(jié)果因為系統(tǒng)代理方法變更引起各種奇怪的 bug

建議升級版本時,先搞定已變更的代理方法

4.1 -> 4.2同樣也有方法變更间涵,以下是我遷移過程中發(fā)現(xiàn)的變更仁热,如有遺漏,歡迎補充:

### UIImagePickerControllerDelegate

在 Swift 4.2 中 `UIImagePickerControllerReferenceURL`? `UIImagePickerControllerOriginalImage` 等由常量變?yōu)榱?Struct:

```

public struct InfoKey : Hashable, Equatable, RawRepresentable {

? ? public init(rawValue: String)

}

```

所以以下方法也需要跟著修改勾哩,如果不改是不會執(zhí)行該代理方法的:

```

// Swift 4.1

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

```

改為:

```

// Swift 4.2

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])

```

### AppDelegate

同理抗蠢,還有 AppDelegate 中的方法:

#### 1

```

// Swift 4.1

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

```

修改為:

```

// Swift 4.2

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool

```

#### 2

```

// Swift 4.1

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool

```

修改為:

```

// Swift 4.2

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool

```

#### 3

```

// Swift 4.1

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool

```

修改為:

```

// Swift 4.2

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool

```

## 其他變更

以下是我在升級過程中遇到的變更情況,大致整理為「通知相關(guān)思劳,常量變更物蝙,類型變更,方法變更」四類敢艰,共大家參考:

## 通知相關(guān)

#### Notification.Name.UIApplicationWillResignActive

```

// Swift 4.1

Notification.Name.UIApplicationWillResignActive

```

```

// Swift 4.2

UIApplication.willResignActiveNotification

```

#### Notification.Name.UITextViewTextDidChange

```

// Swift 4.1

Notification.Name.UITextFieldTextDidChange

```

```

// Swift 4.2

UITextField.textDidChangeNotification

```

#### Notification.Name.UIKeyboardWillShow

```

// Swift 4.1

Notification.Name.UIKeyboardWillShow

```

```

// Swift 4.2

UIResponder.keyboardWillShowNotification

```

#### Notification.Name.UIKeyboardWillHide

```

// Swift 4.1

Notification.Name.UIKeyboardWillHide

```

```

// Swift 4.2

UIResponder.keyboardWillHideNotification

```

## 常量變更

##### UILayoutFittingExpandedSize

```

UIKIT_EXTERN const CGSize UILayoutFittingCompressedSize NS_AVAILABLE_IOS(6_0);

UIKIT_EXTERN const CGSize UILayoutFittingExpandedSize NS_AVAILABLE_IOS(6_0);

```

UILayoutFittingExpandedSize 由常量變?yōu)榱薝IView 的 class 屬性

```

// Swift 4.1

UILayoutFittingExpandedSize

```

```

// Swift 4.2

UIView.layoutFittingExpandedSize

```

```

// Swift 4.1

UILayoutFittingCompressedSize

```

```

// Swift 4.2

UIView.layoutFittingCompressedSize

```

##### AVAudioSessionRouteChangeReason

```

// Swift 4.1

AVAudioSessionRouteChangeReason

```

```

// Swift 4.2

AVAudioSession.RouteChangeReason

```

#### UIKeyboardFrameEndUserInfoKey

```

// Swift 4.1

UIKeyboardFrameEndUserInfoKey

```

```

// Swift 4.2

UIResponder.keyboardFrameEndUserInfoKey

```

#### UIKeyboardAnimationDurationUserInfoKey

```

// Swift 4.1

UIKeyboardAnimationDurationUserInfoKey

```

```

// Swift 4.2

UIResponder.keyboardAnimationDurationUserInfoKey

```

#### UIKeyboardAnimationCurveUserInfoKey

```

// Swift 4.1

UIKeyboardAnimationCurveUserInfoKey

```

```

// Swift 4.2

UIResponder.keyboardAnimationCurveUserInfoKey

```

#### kCAFillModeForwards

```

// Swift 4.1

kCAFillModeForwards

```

```

// Swift 4.2

CAMediaTimingFillMode.forwards

```

#### kCAMediaTimingFunctionEaseInEaseOut

```

// Swift 4.1

kCAMediaTimingFunctionEaseInEaseOut

```

```

// Swift 4.2

CAMediaTimingFunctionName.easeInEaseOut

```

#### kCALineJoinMiter

```

// Swift 4.1

kCALineJoinMiter

```

```

// Swift 4.2

CAShapeLayerLineJoin.miter

```

### 幾種從 String 常量變?yōu)?Struct 類型

#### UIImagePickerControllerReferenceURL

```

// Swift 4.1

UIImagePickerControllerReferenceURL

```

```

// Swift 4.2

UIImagePickerController.InfoKey.referenceURL

```

#### UIImagePickerControllerOriginalImage

```

// Swift 4.1

UIImagePickerControllerOriginalImage

```

```

// Swift 4.2

UIImagePickerController.InfoKey.originalImage

```

#### UIImagePickerControllerCropRect

```

// Swift 4.1

UIImagePickerControllerCropRect

```

```

// Swift 4.2

UIImagePickerController.InfoKey.cropRect

```

#### UIImagePickerControllerMediaType

```

// Swift 4.1

UIImagePickerControllerMediaType

```

```

// Swift 4.2

UIImagePickerController.InfoKey.mediaType

```

## 類型變更

##### UITableViewCellStyle

```

// Swift 4.1

UITableViewCellStyle

```

```

// Swift 4.2

UITableViewCell.CellStyle

```

##### UIWindowLevelAlert

```

// Swift 4.1

UIWindowLevelAlert

```

```

// Swift 4.2

UIWindow.Level.alert

```

##### UIViewAnimationCurve

```

// Swift 4.1

UIViewAnimationCurve

```

```

// Swift 4.2

UIView.AnimationCurve

```

##### UIAlertActionStyle

```

// Swift 4.1

UIAlertActionStyle

```

```

// Swift 4.2

UIAlertAction.Style

```

##### UIViewContentMode

```

// Swift 4.1

UIViewContentMode

```

```

// Swift 4.2

UIView.ContentMode

```

##### RunLoopMode

```

// Swift 4.1

RunLoopMode

```

```

// Swift 4.2

RunLoop.Mode

```

##### NSAttributedStringKey

```

// Swift 4.1

NSAttributedStringKey

```

```

// Swift 4.2

NSAttributedString.Key

```

##### UIViewAnimationOptions

```

// Swift 4.1

UIViewAnimationOptions

```

```

// Swift 4.2

UIView.AnimationOptions

```

##### UITableViewAutomaticDimension

```

// Swift 4.1

UITableViewAutomaticDimension

```

```

// Swift 4.2

UITableView.automaticDimension

```

##### UIApplicationLaunchOptionsKey

```

// Swift 4.1

UIApplicationLaunchOptionsKey

```

```

// Swift 4.2

UIApplication.LaunchOptionsKey

```

##### UICollectionViewScrollPosition

```

// Swift 4.1

UICollectionViewScrollPosition

```

```

// Swift 4.2

UICollectionView.ScrollPosition

```

##### UIApplicationOpenURLOptionsKey

```

// Swift 4.1

UIApplicationOpenURLOptionsKey

```

```

// Swift 4.2

UIApplication.OpenURLOptionsKey

```

##### UIViewAutoresizing

```

// Swift 4.1

UIViewAutoresizing

```

```

// Swift 4.2

UIView.AutoresizingMask

```

##### AVPlayerStatus

```

// Swift 4.1

AVPlayerStatus

```

```

// Swift 4.2

AVPlayer.Status

```

##### NSUnderlineStyle

NSUnderlineStyle寫法更簡潔了

```

// Swift 4.1

NSUnderlineStyle.styleSingle

```

```

// Swift 4.2

NSUnderlineStyle.single

```

##### UIButtonType

```

// Swift 4.1

UIButtonType

```

```

// Swift 4.2

UIButton.ButtonType

```

##### UIControlState

```

// Swift 4.1

UIControlState

```

```

// Swift 4.2

UIControl.State

```

##### UIControlEvents

```

// Swift 4.1

UIControlEvents

```

```

// Swift 4.2

UIControl.Event

```

##### UIAlertControllerStyle

```

// Swift 4.1

UIAlertControllerStyle

```

```

// Swift 4.2

UIAlertController.Style

```

##### UICollectionElementKindSectionHeader

```

// Swift 4.1

UICollectionElementKindSectionHeader

```

```

// Swift 4.2

UICollectionView.elementKindSectionHeader

```

```

// Swift 4.1

UICollectionElementKindSectionFooter

```

```

// Swift 4.2

UICollectionView.elementKindSectionFooter

```

##### UIBarButtonItemStyle

```

// Swift 4.1

UIBarButtonItemStyle

```

```

// Swift 4.2

UIBarButtonItem.Style

```

##### NSAttributedStringKey

```

// Swift 4.1

NSAttributedStringKey

```

```

// Swift 4.2

NSAttributedString.Key

```

##### UIApplicationOpenSettingsURLString

```

// Swift 4.1

UIApplicationOpenSettingsURLString

```

```

// Swift 4.2

UIApplication.openSettingsURLString

```

## 方法變更

#### MKCoordinateRegionMake(CLLocationCoordinate2D centerCoordinate, MKCoordinateSpan span)

```

// Swift 4.1

MKCoordinateRegionMake(a, b)

```

```

// Swift 4.2

MKCoordinateRegion(center: a, span: b)

```

#### MKCoordinateSpanMake(CLLocationDegrees latitudeDelta, CLLocationDegrees longitudeDelta)

```

// Swift 4.1

MKCoordinateSpanMake(0.1, 0.1)

```

```

// Swift 4.2

MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)

```

#### UIAccessibilityIsVoiceOverRunning()

```

// Swift 4.1

UIAccessibilityIsVoiceOverRunning()

```

```

// Swift 4.2

UIAccessibility.isVoiceOverRunning

```

#### UIEdgeInsetsMake

```

// Swift 4.1

UIEdgeInsetsMake(10, 0, 40, 0)

```

```

// Swift 4.2

UIEdgeInsets(top: 10, left: 0, bottom: 40, right: 0)

```

#### UIEdgeInsetsInsetRect(rect, insets)

```

// Swift 4.1

UIEdgeInsetsInsetRect(rect, insets)

```

```

// Swift 4.2

rect.inset(by: insets)

```

#### NSStringFromCGPoint(CGPoint point);

```

// Swift 4.1

NSStringFromCGPoint(x)

```

```

// Swift 4.2

NSCoder.string(for: x)

```

#### didMove(toParentViewController:)

```

// Swift 4.1

viewController.didMove(toParentViewController: self)

```

```

// Swift 4.2

viewController.didMove(toParent: self)

```

#### addChildViewController()

```

// Swift 4.1

addChildViewController(viewController)

```

```

// Swift 4.2

addChild(viewController)

```

#### removeFromParentViewController

```

// Swift 4.1

viewController.removeFromParentViewController()

```

```

// Swift 4.2

viewController.removeFromParent()

```

##### var childViewControllers:[UIViewController]

```

// Swift 4.1

let array = viewController.childViewControllers

```

```

// Swift 4.2

let array = viewController.children

```

#### bringSubview(toFront:)

```

// Swift 4.1

bringSubview(toFront: view)

```

```

// Swift 4.2

bringSubviewToFront(view)

```

#### sendSubview(toBack: headerView)

```

// Swift 4.1

sendSubview(toBack: headerView)

```

```

// Swift 4.2

sendSubviewToBack(headerView)

```

##### UIImageJPEGRepresentation(,)

```

// Swift 4.1

let data = UIImageJPEGRepresentation(image, 0.6)

```

```

// Swift 4.2

let data = image.jpegData(compressionQuality: 0.6)

```

##### UIDatePickerMode

```

// Swift 4.1

UIDatePickerMode

```

```

// Swift 4.2

UIDatePicker.Mode

```

##### AVAudioSession.RouteChangeReason

```

// Swift 4.1

UIScrollViewDecelerationRateFast

```

```

// Swift 4.2

UIScrollView.DecelerationRate.fast

```

##### UITableViewCellEditingStyle

```

// Swift 4.1

UITableViewCellEditingStyle

```

```

// Swift 4.2

UITableViewCell.EditingStyle

```

##### AVAudioSessionInterruptionType

```

typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)

{

AVAudioSessionInterruptionTypeBegan = 1,? /* the system has interrupted your audio session */

AVAudioSessionInterruptionTypeEnded = 0,? /* the interruption has ended */

};

```

```

// Swift 4.1

AVAudioSessionInterruptionType

```

```

// Swift 4.2

AVAudioSession.InterruptionType

```

##### CMTimeMake

```

// Swift 4.1

CMTimeMake(0, 1)

```

```

// Swift 4.2

CMTimeMake(value: 0, timescale: 1)

```

#### AVAudioSession setCategory

AVAudioSession的 setCategory不能像之前版本不填寫 mode了诬乞,新版寫法:

```

try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient, mode: .default)

```

以上是我在升級 Swift 4.2 過程中的記錄,如有遺漏钠导,歡迎補充

[我的微博](http://weibo.com/devlcd)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末震嫉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子牡属,更是在濱河造成了極大的恐慌票堵,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逮栅,死亡現(xiàn)場離奇詭異悴势,居然都是意外死亡窗宇,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進店門特纤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來军俊,“玉大人,你說我怎么就攤上這事捧存》喙” “怎么了?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵昔穴,是天一觀的道長镰官。 經(jīng)常有香客問我,道長吗货,這世上最難降的妖魔是什么泳唠? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮宙搬,結(jié)果婚禮上笨腥,老公的妹妹穿的比我還像新娘。我一直安慰自己害淤,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布拓售。 她就那樣靜靜地躺著窥摄,像睡著了一般。 火紅的嫁衣襯著肌膚如雪础淤。 梳的紋絲不亂的頭發(fā)上崭放,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天,我揣著相機與錄音鸽凶,去河邊找鬼币砂。 笑死,一個胖子當(dāng)著我的面吹牛玻侥,可吹牛的內(nèi)容都是我干的决摧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼凑兰,長吁一口氣:“原來是場噩夢啊……” “哼掌桩!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起姑食,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤波岛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后音半,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體则拷,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡贡蓖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了煌茬。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片斥铺。...
    茶點故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖宣旱,靈堂內(nèi)的尸體忽然破棺而出仅父,到底是詐尸還是另有隱情,我是刑警寧澤浑吟,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布笙纤,位于F島的核電站,受9級特大地震影響组力,放射性物質(zhì)發(fā)生泄漏省容。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一燎字、第九天 我趴在偏房一處隱蔽的房頂上張望腥椒。 院中可真熱鬧,春花似錦候衍、人聲如沸笼蛛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽滨砍。三九已至,卻和暖如春妖异,著一層夾襖步出監(jiān)牢的瞬間惋戏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工他膳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留响逢,地道東北人。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓棕孙,卻偏偏與公主長得像舔亭,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蟀俊,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容