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



我刚刚更新到 Xcode 9 并将我的应用程序从 swift 3 转换为 swift 4。 我有使用字符串来标记轴和其他变量的图表。 所以我有一个 moneyAxisString = "Money"。 以前我能够使用以下代码绘制它们:

moneyAxisString.draw(in: CGRect(x: CGFloat(coordinateXOriginLT + axisLength/3), y: CGFloat(coordinateYOriginRT + axisLength + 5 * unitDim), width: CGFloat(300 * unitDim), height: CGFloat(100 * unitDim)), withAttributes: attributes as? [String : AnyObject])

其中属性是字典,定义如下

attributes = [
NSAttributedStringKey.foregroundColor: fieldColor,
NSAttributedStringKey.font: fieldFont!,
NSAttributedStringKey.paragraphStyle: style
]

现在我的应用程序无法编译,我收到消息:

无法将类型为"[字符串:任何对象]?"的值转换为预期的参数类型"[NSAttributedStringKey:Any]?"?

这是一种类型不匹配:[String : AnyObject]显然不是[NSAttributedStringKey : Any]

⌥-单击NSAttributedStringKey以查看声明。


解决方案是将attributes声明为

var attributes = [NSAttributedStringKey : Any]()

去除向下铸件

..., withAttributes: attributes)

并简单地写

attributes = [.foregroundColor: fieldColor,
.font: fieldFont!,
.paragraphStyle: style]
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]

请注意,您现在也不需要as!

或者,您可以通过预先声明数组[String : Any]来跳过最后的as转换:

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

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

试试这个:

class func getCustomStringStyle() -> [NSAttributedStringKey: Any]
{
return [
NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): UIFont.systemFont(ofSize: 16), // or your fieldFont
NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor.black, // or your fieldColor
NSAttributedStringKey(rawValue: NSAttributedStringKey.paragraphStyle.rawValue): NSParagraphStyle.default // or your style
]
}

或:

class func getCustomStringStyle() -> [String: Any]
{
return [
NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 16),
NSAttributedStringKey.foregroundColor.rawValue: UIColor.black,
NSAttributedStringKey.paragraphStyle.rawValue:NSParagraphStyle.default
]
}

Swift 4.2
建立在user_Dennis的例子之上

func getCustomStringStyle() -> [NSAttributedString.Key: Any]
{
return [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): UIFont.systemFont(ofSize: 25), // or your fieldFont
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.black, // or your fieldColor
NSAttributedString.Key(rawValue: NSAttributedString.Key.paragraphStyle.rawValue): NSParagraphStyle.default // or your style
]
}

最新更新