升级 Swift 4.2 教程

如果喜欢这篇文章,欢迎点赞或者点个关注:[我的微博](http://weibo.com/devlcd) ,以后发布文章,会第一时间在微博通知

## 依赖库

> 如果你看的时候项目依赖的所有库都支持了 Swift 4.2 请忽略这部分内容,直接从下节开始

因为现在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

## 系统代理方法变更

每次升级 Swift 最坑的就是系统代理方法变更,而自己没有发现,修改完语法之后以为没问题,结果因为系统代理方法变更引起各种奇怪的 bug

建议升级版本时,先搞定已变更的代理方法

4.1 -> 4.2同样也有方法变更,以下是我迁移过程中发现的变更,如有遗漏,欢迎补充:

### UIImagePickerControllerDelegate

在 Swift 4.2 中 `UIImagePickerControllerReferenceURL`  `UIImagePickerControllerOriginalImage` 等由常量变为了 Struct:

```

public struct InfoKey : Hashable, Equatable, RawRepresentable {

    public init(rawValue: String)

}

```

所以以下方法也需要跟着修改,如果不改是不会执行该代理方法的:

```

// 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

```

## 其他变更

以下是我在升级过程中遇到的变更情况,大致整理为「通知相关,常量变更,类型变更,方法变更」四类,共大家参考:

## 通知相关

#### 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 由常量变为了UIView 的 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 常量变为 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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容