iOS 条件绑定的初始化器必须是 Optional 类型,而不是 'CGFont'?

iOS Initializer for conditional binding must have Optional type, not 'CGFont'?

当我将 Uber SDK 集成到我的项目中时,我在 swift 2.3 中遇到了这个错误,但我不知道如何解决这个问题。

class FontUtil {
static func loadFontWithName(name: String, familyName: String) -> Bool {
    if let path = NSBundle(forClass: FontUtil.self).pathForResource(name, ofType: "otf") {
        if let inData = NSData(contentsOfFile: path) {
            var error: Unmanaged<CFError>?
            let cfdata = CFDataCreate(nil, UnsafePointer<UInt8>(inData.bytes), inData.length)
            if let provider = CGDataProviderCreateWithCFData(cfdata) {
                if let font = CGFontCreateWithDataProvider(provider) ---> Error found in this line {
                    if (CTFontManagerRegisterGraphicsFont(font, &error)) {
                        return true
                    }
                    print("Failed to load font with error: \(error)")
                }
            }
        }
    }
    return false
}}

正如 Eric 所说,CGFontCreateWithDataProvider 函数不再返回 Optional 值,因此您无需将此语句和后续调用包装在 if 可选捆绑。您的代码将更改为:

let font = CGFontCreateWithDataProvider(provider)
if (CTFontManagerRegisterGraphicsFont(font, &error)) {
  return true
}
print("Failed to load font with error: \(error)")