swift4.0 适配
来源:互联网 发布:2017双11淘宝销售额 编辑:程序博客网 时间:2024/05/17 14:14
一、前言
在我们的工程中处于swift
和OC
混编的状态,使用swift
已经有一年半的时间了,随着Xcode9
的更新,swift3.2
和swift4.0
也随之到来,swift3.2
相较于Xcode8
的swift3.1
变动极小,适配没遇到问题,主要关注swift4.0
的适配。
二、查看当前工程的 swift 版本
三、使用 Xcode 将工程转换到 swift4.0
1、环境
- Xcode9.1
- 当前
swift
版本 3.2
2、转换步骤:
- 选中要转换的
target
- Edit -> Convert -> To Current Swift Syntax
- 勾选需要转换的
target
(pod
引用不用勾选),Next 选择转换选项,Next
这两个选项是关于swift
的@objc
推断特性的,如果使用了swift4.0
显式的@objc
属性,能减少整体代码的大小。此时我们选 Minimize Inference(recommend),
关于两个选项:Minimize Inference(recommend)
根据静态推断,仅在需要的地方添加@objc属性。使用此选项后,需要按照Completing a Swift 4 minimize inference migration来完成转换。Match Swift 3 Behavior
在编译器隐式推断的任何地方向代码添加一个@objc属性。这个选项不会改变你的二进制文件的大小,因为被Swift 3隐式推断在所有的地方都添加了显式的@objc属性。
预览转换代码,没问题,Save。
3、修改错误
完成上述5步之后,看一下 swift
版本,已经是4.0了:
至此打完收工,适配结束。然而并没有,当你运行的时候会看到这个:
是否欲哭无泪,居然这么多错误,不用怕,其实要改动的地方并不多,有些都是重复的,可以直接全局替换就行。
举个栗子:
- class dynamic func
// 转换前class dynamic func bookMoneyToUpController() -> MPBookMoneyToUpController { let vc = MPBookMoneyToUpController.init(nibName: "MPBookMoneyToUpController", bundle: Bundle.main) return vc}// 转换后class @objc dynamic func bookMoneyToUpController() -> MPBookMoneyToUpController { let vc = MPBookMoneyToUpController.init(nibName: "MPBookMoneyToUpController", bundle: Bundle.main) return vc}// 问题 @objc 修饰符需要前置// 修改成下面即可@objc class dynamic func bookMoneyToUpController() -> MPBookMoneyToUpController { let vc = MPBookMoneyToUpController.init(nibName: "MPBookMoneyToUpController", bundle: Bundle.main) return vc}// 全局替换即可class @objc dynamic func -> @objc class dynamic func
注:
上面使用 dynamic
修饰符是由于以前使用 JSPatch
来做 hotfix
,需要用到原来OC的运行时特性。
四、@objc
swift4.0
最大的特性之一就是 @objc
修饰符的变化了,它主要处理 OC
和 swift
混编时一些方法的调用以及属性获取问题,swift4.0
将在 swift3.x
中一些隐式类型推断的特性去除以后,需要我们来手动管理 @objc
修饰符。
在上文中使用 Xcode
转换 swift4.0
时我们勾选了 Minimize Inference
选项,那么我们就需要手动处理相关的 @objc
修饰符,来保证 OC
和 swift
代码能正常相互调用。
1、@objc
修饰符手动处理步骤
使用“最小化”转换代码后,需要处理构建和运行时的问题,在完成初始的 swift4.0
转换后,需要按照下面步骤来处理其它问题。
1. 运行你的工程
2. 修复编译器提示需要添加 @objc
的地方
3. 测试你的代码,并修复编译器提示使用了不推荐的隐式 @objc
引用的警告。直到没有警告发生。
打开工程的 build settings.
将
Swift 3 @objc inference
设置为Default
.
2、@objc
修饰符需要处理的问题
- 编译警告
- swift 中编译的警告
#selector
参数指定的实例方法必须使用@objc
修饰,因为swift4
中弃用了@objc
属性推断。
- swift 中编译的警告
// 下面的代码会有警告class MyClass : NSObject { func foo() { } func bar() { self.perform(#selector(MyClass.foo) }}warning: argument of ‘#selector’ refers to instance method ‘foo’ in ‘MyClass’ that depends on ‘@objc’ attribute inference deprecated in Swift 4
- Objective-C 编译时警告
在OC
中调用的swift
方法,在swift
中需要追加@objc
修饰,swift4
废弃了该类型推断。
// 下面的代码会有警告@implementation MyClass (ObjCMethods)- (void)other { [self foo]; }@endwarning: Swift method MyClass.foo uses @objc inference deprecated in Swift 4; add @objc to provide an Objective-C entrypoint
- 修复编译时警告
// 通过追加 @objc 来消除警告class MyClass : NSObject { @objc func foo() { } func bar() { self.perform(#selector(MyClass.foo) }}
查看所有需要添加
@objc
的编译警告
直接选中定位到相应位置,追加@objc
修饰即可。- 运行时警告
运行时警告会打印在控制台:
- 运行时警告
***Swift runtime: ClassName.swift:lineInFile:columnInLine: entrypoint -[ClassName methodName] generated by implicit @objc inference is deprecated and will be removed in Swift 4; add explicit @objc to the declaration to emit the Objective-C entrypoint in Swift 4 and suppress this message
在 Xcode9.1
中,运行时警告在这里也能看到:
想要修复运行时警告,需要添加 @objc
修饰符到对应的方法或者符号。
运行时警告的常见原因:
- 在
OC
中使用SEL
- 在
swift
中使用了perform methods
- 在
OC
中使用了performSelector methods
- 使用了
@IBOutlet
或者@IBAction
- 在
// 下面 swift 代码会产生运行时警告class MyClass : NSObject { func foo() { } func bar() { let selectorName = "foo" self.perform(Selector(selectorName) }}***Swift runtime: MyClass.swift:7:7: entrypoint -[MyClass foo] generated by implicit @objc inference is deprecated and will be removed in Swift 4; add explicit @objc to the declaration to emit the Objective-C entrypoint in Swift 4 and suppress this message
五、swift4.0
其它部分特性
1、NSAttributedStringKey
NSAttributedString
的初始化方法变化:
// swift3.xpublic init(string str: String, attributes attrs: [AnyHashable : Any]? = nil)// swift4.0public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)
示例:
// 转换前let attributes = [NSForegroundColorAttributeName: RGB(128, g: 134, b: 146), NSParagraphStyleAttributeName: paragraph, NSFontAttributeName: UIFont.systemFont(ofSize: 14)] as [String : Any]var tipAttrText = NSAttributedString.init(string: tipText, attributes: attributes)// 转换后let attributes = [NSAttributedStringKey.foregroundColor.rawValue: RGB(128, g: 134, b: 146), NSAttributedStringKey.paragraphStyle: paragraph, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)] as! [String : Any]var tipAttrText = NSAttributedString(string: tipText, attributes: attributes)// tipAttrText 初始化报错提示Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?'// 修改NSAttributedStringKey.foregroundColor.rawValue -> NSAttributedStringKey.foregroundColor去掉 as! [String : Any]
2、String
String
的characters
属性被废弃了
let string = "abc"var count = string.characters.count// 第二行报错'characters' is deprecated: Please use String or Substring directly// 对应新方法count = string.count
String
的addingPercentEscapes
方法被废弃了
// swift3.xvar url = @"http://www.example.com?username=姓名"url = url.addingPercentEscapes(using: String.Encoding.utf8)!// 报错'addingPercentEscapes(using:)' is unavailable: Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.// 修改uri = uri.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
substring(to:)
被废弃了
let index = tagText.index(tagText.startIndex, offsetBy: MPMultipleStyleListItemTagMaxLength)// 警告:'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upto' operator.let b = tagText.substring(to: index)// 新 API// 注意:a 的类型是 Substring,不是 Stringlet a = tagText.prefix(upTo: index)
3、initialize 废弃
// swift3.xoverride class func initialize() { // some code}// 报错Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift
Swift3.x 继续 Method Swizzling这篇文章里面介绍了一种解决思路。
4、swift3
使用 #selector
指定的方法,只有当方法权限为 private
时需要加 @objc
修饰符,swift4.0
都要加 @objc
修饰符
// 示例代码func startMonitor() { NotificationCenter.default.addObserver(self, selector: #selector(self.refreshUserLoginStatus), name: NSNotification.Name.XSLUserLogin, object: nil)}func refreshUserLoginStatus() { // some code}// 第二行警告Argument of '#selector' refers to instance method 'refreshUserLoginStatus()' in 'MPUnreadMessageCountManager' that depends on '@objc' inference deprecated in Swift 4// 追加 privatefunc startMonitor() { NotificationCenter.default.addObserver(self, selector: #selector(self.refreshUserLoginStatus), name: NSNotification.Name.XSLUserLogin, object: nil)}private func refreshUserLoginStatus() { // some code}// 第二行报错Argument of '#selector' refers to instance method 'refreshUserLoginStatus()' that is not exposed to Objective-C
swift4.0
不再允许重载extension
中的方法(包括instance
、static
、class
方法)
// 示例代码class TestSuperClass: NSObject {}extension TestSuperClass { func test() { // some code }}class TestClass: TestSuperClass { // 报错:Declarations from extensions cannot be overridden yet override func test() { // some code }}
六、pod
引用
添加以下内容到 Podfile
。
post_install do |installer| installer.pods_project.targets.each do |target| if ['WTCarouselFlowLayout', 'XSLRevenue', 'OHHTTPStubs/Swift'].include? target.name target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '3.2' end end endend
七、踩坑
UITableViewDelegate
协议方法名变更,没有错误提示:
// swift3.xfunc tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat // swift4.0func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
- swift4.0 适配
- 最新:适配Xcode9.0与Swift4.0
- swift4.0 涂鸦画板
- swift4.0 UIButton小解
- swift4.0 新特性
- Swift4.0 — 属性
- Swift4.0枚举基础知识
- Swift4.0 字符串操作
- Swift4.0开发笔记
- 【Swift4.0】基础部分
- 【Swift4.0】可选类型
- Swift4
- Swift4
- Swift4
- Swift4
- swift4
- swift4.0自定义UITabBarController +UINavigationController
- swift4.0 Any 和 AnyObject
- mui初级入门教程(三)— html5+ XMLHttpRequest 与mui ajax用法详解
- Servlet+Tomcat搭建Http服务
- C++之整形
- ORACLE中的rownum
- 知识汇总二(简单光照模型)
- swift4.0 适配
- ES6学习笔记(ES6新增的数组方法)
- java作业
- [日推荐]『花瓣lite』陪你做生活的设计师
- 上传项目到svn
- 11.9学习心得
- Spark简单处理Apache日志
- JMS------zookeeper的简单安装
- ORACLE快速插入一千万初始数据和删除重复数据