#一、前言
在我们的工程中处于
和
- swift
混编的状态,使用
- OC
已经有一年半的时间了,随着
- swift
的更新,
- Xcode9
和
- swift3.2
也随之到来,
- swift4.0
相较于
- swift3.2
的
- Xcode8
变动极小,适配没遇到问题,主要关注
- swift3.1
的适配。
- swift4.0
#二、查看当前工程的 swift 版本
#三、使用 Xcode 将工程转换到 swift4.0
###1、环境
版本 3.2
- swift
- target
(
- target
引用不用勾选),Next
- pod
的
- swift
推断特性的,如果使用了
- @objc
显式的
- swift4.0
属性,能减少整体代码的大小。此时我们选 Minimize Inference(recommend),
- @objc
###3、修改错误
完成上述5步之后,看一下
版本,已经是4.0了:
- swift
至此打完收工,适配结束。然而并没有,当你运行的时候会看到这个:
是否欲哭无泪,居然这么多错误,不用怕,其实要改动的地方并不多,有些都是重复的,可以直接全局替换就行。
举个栗子:
// 转换后
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
- ![image.png](http://upload-images.jianshu.io/upload_images/2027951-a3bff567cb68f026.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)
- **注**:
- 上面使用 `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``` 引用的警告。直到没有警告发生。
- 4. 打开工程的 [build settings](https://help.apple.com/xcode/mac/9.0/index.html?localePath=en.lproj#/dev06a00ef1d).
- 5. 将 `Swift 3 @objc inference` 设置为 `Default`.
- ### 2、```@objc``` 修饰符需要处理的问题
- 1. 编译警告
- - swift 中编译的警告
- `#selector` 参数指定的实例方法必须使用 `@objc` 修饰,因为`swift4`中弃用了 `@objc`属性推断。
// 下面的代码会有警告
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)
}@endwarning: Swift method MyClass.foo uses @objc inference deprecated in Swift 4; add @objc to provide an Objective-C entrypoint```
- [self foo];
- // 通过追加 @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.x
- public init(string str: String, attributes attrs: [AnyHashable: Any] ? =nil)
- // swift4.0
- public 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.x
- var 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,不是 String
- let a = tagText.prefix(upTo: index)
###3、initialize 废弃
- // swift3.x
- override 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
- // 追加 private
- func 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
- end
- end
#七、踩坑
协议方法名变更,没有错误提示:
- UITableViewDelegate
- // swift3.x
- func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) - >CGFloat
- // swift4.0
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) - >CGFloat
来源: https://juejin.im/post/5a056079f265da432717b10b