ios – Swift 4向后兼容性

我在 Xcode 8.3.3( Swift 3.1)的项目中有以下代码
let font = CGFont(provider!)
CTFontManagerRegistergraphicsFont(font,&error)

但是在Xcode 9 Beta(Swift 4)中,我收到以下错误

Value of optional type ‘CGFont?’ not unwrapped; did you mean to use
‘!’ or ‘?’?

错误是因为采用CGDataProvider的initializer for CGFont现在返回一个可选项.

但是,当我应用修复:

let font = CGFont(provider)
CTFontManagerRegistergraphicsFont(font!,&error)

代码不再使用Swift 3.1在Xcode 8.3.3中编译,因为字体不是可选的,因此不能很好地与!一起使用.

有没有办法在两个版本的Xcode中使这个工作? Swift 4是否应该向后兼容(使用Swift 3编译器编译)?

解决方法

这是Core Graphics的一个重大变化,而不是Swift本身. API已更改,初始化程序现在可以使用.

使用conditional compilation使用3.1和4.0编译器编译代码

#if swift(>=4.0)
let font = CGFont(provider!)
#else
let font = CGFont(provider)!
#endif

CTFontManagerRegistergraphicsFont(font,&error)

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...