swift4.0 适配

来源:互联网 发布:2017双11淘宝销售额 编辑:程序博客网 时间:2024/05/17 14:14

一、前言

在我们的工程中处于swiftOC混编的状态,使用swift已经有一年半的时间了,随着Xcode9的更新,swift3.2swift4.0也随之到来,swift3.2相较于Xcode8swift3.1变动极小,适配没遇到问题,主要关注swift4.0的适配。

二、查看当前工程的 swift 版本

image.png

三、使用 Xcode 将工程转换到 swift4.0

1、环境

  • Xcode9.1
  • 当前 swift 版本 3.2

2、转换步骤:

  1. 选中要转换的 target
  2. Edit -> Convert -> To Current Swift Syntax
    image.png
  3. 勾选需要转换的 targetpod 引用不用勾选),Next
    image.png
  4. 选择转换选项,Next
    这两个选项是关于 swift@objc 推断特性的,如果使用了 swift4.0 显式的 @objc 属性,能减少整体代码的大小。此时我们选 Minimize Inference(recommend),
    image.png
    关于两个选项:

    • Minimize Inference(recommend)
      根据静态推断,仅在需要的地方添加@objc属性。使用此选项后,需要按照Completing a Swift 4 minimize inference migration来完成转换。

    • Match Swift 3 Behavior
      在编译器隐式推断的任何地方向代码添加一个@objc属性。这个选项不会改变你的二进制文件的大小,因为被Swift 3隐式推断在所有的地方都添加了显式的@objc属性。

  5. 预览转换代码,没问题,Save。

3、修改错误

完成上述5步之后,看一下 swift 版本,已经是4.0了:
image.png

至此打完收工,适配结束。然而并没有,当你运行的时候会看到这个:
image.png

是否欲哭无泪,居然这么多错误,不用怕,其实要改动的地方并不多,有些都是重复的,可以直接全局替换就行。

举个栗子:
- 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

image.png


上面使用 dynamic 修饰符是由于以前使用 JSPatch 来做 hotfix,需要用到原来OC的运行时特性。

四、@objc

swift4.0 最大的特性之一就是 @objc 修饰符的变化了,它主要处理 OCswift 混编时一些方法的调用以及属性获取问题,swift4.0 将在 swift3.x 中一些隐式类型推断的特性去除以后,需要我们来手动管理 @objc 修饰符。
在上文中使用 Xcode 转换 swift4.0 时我们勾选了 Minimize Inference 选项,那么我们就需要手动处理相关的 @objc 修饰符,来保证 OCswift 代码能正常相互调用。

1、@objc 修饰符手动处理步骤

使用“最小化”转换代码后,需要处理构建和运行时的问题,在完成初始的 swift4.0 转换后,需要按照下面步骤来处理其它问题。
1. 运行你的工程
2. 修复编译器提示需要添加 @objc 的地方
3. 测试你的代码,并修复编译器提示使用了不推荐的隐式 @objc 引用的警告。直到没有警告发生。

  1. 打开工程的 build settings.

  2. 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 methodfooinMyClassthat depends on ‘@objcattribute 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 的编译警告
    image.png
    直接选中定位到相应位置,追加 @objc 修饰即可。

    1. 运行时警告
      运行时警告会打印在控制台:
***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 中,运行时警告在这里也能看到:
image.png

想要修复运行时警告,需要添加 @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

  • Stringcharacters 属性被废弃了
let string = "abc"var count = string.characters.count// 第二行报错'characters' is deprecated: Please use String or Substring directly// 对应新方法count = string.count
  • StringaddingPercentEscapes 方法被废弃了
// 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 中的方法(包括instancestaticclass方法)
// 示例代码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 
原创粉丝点击