swift4.0 适配

原文地址:swift4.0 适配


一、前言

在我们的工程中处于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属性推断。

// 下面的代码会有警告
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

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的编译警告

直接选中定位到相应位置,追加@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

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

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

推荐阅读更多精彩内容

  • 一、前言 在我们的工程中处于swift和OC混编的状态,使用swift已经有一年半的时间了,随着Xcode9的更新...
    wentianen阅读 2,673评论 0 4
  • 1、随机数 不需要随机数种子 arc4random()%N + begin:产生begin~begin+N的随机数...
    我是小胡胡分胡阅读 4,004评论 0 2
  • iOS开发中,我们需要根据用户需要去适配各种各样的版本,特别是苹果爸爸的每一次新版本发布,作为开发者的我们永远是最...
    青苹果园阅读 7,498评论 2 12
  • 只为个人记录下来看看 swift4.0 适配 原文地址:http://blog.csdn.net/andanlan...
    拥抱月亮的大星星阅读 345评论 0 1
  • 老教授要带领我们参观图书馆。因为白天人太多,所以选在晚上过去。 我们大约是一个班的人数,由教授和班长领路。班长好像...
    愿河阅读 227评论 0 1