Ios swift 4:无法为类型为';[UIFontDesciptor.AttributeName:Any]';索引类型为';字符串';

Ios swift 4:无法为类型为';[UIFontDesciptor.AttributeName:Any]';索引类型为';字符串';,ios,swift4,uifont,custom-font,Ios,Swift4,Uifont,Custom Font,我试图在这里初始化我的自定义字体,但它显示了错误 extension UIFont { @objc convenience init(myCoder aDecoder: NSCoder) { if let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor { if let fontAttribute = fontDescriptor.fontAtt

我试图在这里初始化我的自定义字体,但它显示了错误

extension UIFont {
@objc convenience init(myCoder aDecoder: NSCoder) {
    if let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor {
        if let fontAttribute = fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String { // HERE SHOWING THE ERROR
            var fontName = ""
            switch fontAttribute {
            case "CTFontRegularUsage":
                fontName = appFontName
            case "CTFontEmphasizedUsage", "CTFontBoldUsage":
                fontName = appFontBoldName
            case "CTFontObliqueUsage":
                fontName = appFontItalicName
            default:
                fontName = appFontName
            }
            self.init(name: fontName, size: fontDescriptor.pointSize)!
        }
        else {
            self.init(myCoder: aDecoder)
        }
    }
    else {
        self.init(myCoder: aDecoder)
    }
}
...
}

这非常适用于swift-3.2。但它并没有运行swift-4.0。请帮帮我。提前感谢。

字体属性标识符的类型已从
String
更改为
UIFontDescriptor.AttributeName

好处是您可以声明扩展

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}
然后你就可以写了

if let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String {
或者没有分机

if let fontAttribute = fontDescriptor.fontAttributes[UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")] as? String {