无标题文章

只为个人记录下来看看

swift4.0 适配

原文地址:
http://blog.csdn.net/andanlan/article/details/78491599?locationNum=1&fps=1

<a name="t0" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>一、前言

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

<a name="t1" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>二、查看当前工程的 swift 版本

image.png

<a name="t2" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>三、使用 Xcode 将工程转换到 swift4.0

<a name="t3" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>1、环境

  • Xcode9.1

  • 当前

    swift

    版本 3.2

<a name="t4" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>2、转换步骤:

  1. 选中要转换的

    target

  2. Edit -> Convert -> To Current Swift Syntax

    image.png
  3. 勾选需要转换的

    target

    pod

    引用不用勾选),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。

<a name="t5" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>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的运行时特性。

<a name="t6" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>四、@objc

swift4.0

最大的特性之一就是

@objc

修饰符的变化了,它主要处理

OC

swift

混编时一些方法的调用以及属性获取问题,swift4.0

将在

swift3.x

中一些隐式类型推断的特性去除以后,需要我们来手动管理

@objc

修饰符。

在上文中使用

Xcode

转换

swift4.0

时我们勾选了

Minimize Inference

选项,那么我们就需要手动处理相关的

@objc

修饰符,来保证

OC

swift

代码能正常相互调用。

<a name="t7" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>1、@objc

修饰符手动处理步骤

使用“最小化”转换代码后,需要处理构建和运行时的问题,在完成初始的

swift4.0

转换后,需要按照下面步骤来处理其它问题。

1. 运行你的工程

2. 修复编译器提示需要添加

@objc

的地方

3. 测试你的代码,并修复编译器提示使用了不推荐的隐式

@objc

引用的警告。直到没有警告发生。

  1. 打开工程的

    build settings.

  2. Swift 3 @objc inference

    设置为

    Default.

<a name="t8" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>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)
- (void)other {
      [self foo];
   }
@end
warning: 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

<a name="t9" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>五、swift4.0

其它部分特性

<a name="t10" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>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]

<a name="t11" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>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)

<a name="t12" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>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这篇文章里面介绍了一种解决思路。

<a name="t13" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>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

    中的方法(包括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
    }
}

<a name="t14" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>六、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

<a name="t15" style="box-sizing: border-box; background: transparent; color: rgb(79, 161, 219); text-decoration: none; margin: 0px; padding: 0px; font-weight: 400; outline: 0px;"></a>七、踩坑

UITableViewDelegate

协议方法名变更,没有错误提示:

// swift3.x
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat 

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

推荐阅读更多精彩内容