本文介绍了Swift 4 转换错误 - NSAttributedStringKey: Any的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近转换了我的应用程序,但不断收到错误

I converted my app recently and I keep getting the error

无法将 '[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
}

推荐答案

为什么会出现这个错误

以前,您的 attributes 定义为 [String: Any],其中键来自 NSAttributedStringKey 作为字符串或 Swift 4.2 中的 NSAttributedString.Key

Why you got this error

Previously, your attributes is defined as [String: Any], where the key comes from NSAttributedStringKey as a string or NSAttributedString.Key in Swift 4.2

在迁移期间,编译器尝试保留 [String: Any] 类型.然而,NSAttributedStringKey 在 swift 4 中变成了一个结构体.因此编译器试图通过获取其原始值来将其更改为字符串.

During the migration, the compiler tries to keep the [String: Any] type. However, NSAttributedStringKey becomes a struct in swift 4. So the compiler tries to change that to string by getting its raw value.

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

In this case, setTitleTextAttributes is looking for [NSAttributedStringKey: Any] but you provided [String: Any]

删除 .rawValue 并将您的 attributes 转换为 [NSAttributedStringKey: Any]

Remove .rawValue and cast your attributes as [NSAttributedStringKey: Any]

即,更改此行

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

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

在 Swift 4.2 中,

And in Swift 4.2,

 let attributes = [NSAttributedString.Key.font:
    UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedString.Key.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any]

这篇关于Swift 4 转换错误 - NSAttributedStringKey: Any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:49