Swift 4转换错误 - NSAttributedStringKey:Any

Eaz*_*azy 29 swift4

我最近转换了我的应用程序并且一直收到错误

"无法将'[String:Any]'类型的值转换为预期的参数类型'[NSAttributedStringKey:Any]?"

barButtonItem.setTitleTextAttributes(attributes, for: .normal)

整码:

 class func getBarButtonItem(title:String) -> UIBarButtonItem {
    let barButtonItem = UIBarButtonItem.init(title: title, style: .plain, target: nil, action: nil)
    let attributes = [NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
    barButtonItem.setTitleTextAttributes(attributes, for: .normal)

    return barButtonItem
}
Run Code Online (Sandbox Code Playgroud)

Fan*_*ing 48

为什么会出现此错误

以前,您attributes的定义为[String: Any],密钥来自NSAttributedStringKey字符串.

在迁移期间,编译器会尝试保留NSAttributedString.Key类型.但是,[String: Any]成为swift 4中的结构.因此编译器尝试通过获取其原始值将其更改为字符串.

在这种情况下,NSAttributedStringKey正在寻找,setTitleTextAttributes但你提供[NSAttributedStringKey: Any]

要修复此错误:

删除[String: Any]并投射你.rawValueattributes

即,更改以下行

let attributes = [NSAttributedStringKey.font.rawValue:
    UIFont(name: "Helvetica-Bold", size: 15.0)!, 
    NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
Run Code Online (Sandbox Code Playgroud)

let attributes = [NSAttributedStringKey.font:
    UIFont(name: "Helvetica-Bold", size: 15.0)!, 
    NSAttributedStringKey.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any]
Run Code Online (Sandbox Code Playgroud)


Vin*_*App 15

它期待NSAttributedStringKey(NSAttributedStringKey.font)你正在发送String(NSAttributedStringKey.font.rawValue).

所以,请更换NSAttributedStringKey.font.rawValueNSAttributedStringKey.font象下面这样:

let attributes = [NSAttributedStringKey.font:  UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white]
Run Code Online (Sandbox Code Playgroud)


lea*_*nne 5

如前面的答案中所述,NSAttributedStringKey在Swift 4中更改为结构.但是,显然使用的 其他对象NSAttributedStringKey没有同时更新.

无需更改任何其他代码,最简单的修复是附加 .rawValue所有出现的NSAttributedStringKeysetter - 将键名转换为Strings:

let attributes = [
    NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedStringKey.foregroundColor.rawValue: UIColor.white
] as [String : Any]
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要!as现在,无论是.

或者,您可以as通过声明阵列是[String : Any]最前面的来跳过最后的演员:

let attributes: [String : Any] = [
    NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedStringKey.foregroundColor.rawValue: UIColor.white
]
Run Code Online (Sandbox Code Playgroud)

当然,您仍然需要为您设置的.rawValue每个NSAttributedStringKey项目附加.