swift 4: 无法使用 'String' 类型的索引下标 '[UIFontDesciptor.AttributeName : Any]' 类型的值

swift 4: cannot subscript a value of type '[UIFontDesciptor.AttributeName : Any]' with an index of type 'String'

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

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 {