我在我的项目中使用下面的代码。更新到swift 4后,我收到错误。我该如何解决?
代码:
let returnString : NSAttributedString
if styleList.count > 0
{
var attrs = [String:AnyObject]()
attrs[NSAttributedStringKey.font] = codeFont
for style in styleList
{
if let themeStyle = themeDict[style]
{
for (attrName, attrValue) in themeStyle
{
attrs.updateValue(attrValue, forKey: attrName)
}
}
}
returnString = NSAttributedString(string: string, attributes:attrs )
}
以下是错误:
无法使用类型为“NSAttributedStringKey”的索引下标“[String:AnyObject]”类型的值
无法将'[String:AnyObject]'类型的值转换为预期的参数类型'[NSAttributedStringKey:Any]?'
答案 0 :(得分:7)
在swift 4中 - NSAttributedString表示已完全更改。
将您的属性字典attrs
用[String:AnyObject]
[NSAttributedStringKey:Any]
试试这个:
let returnString : NSAttributedString
if styleList.count > 0
{
var attrs = [NSAttributedStringKey:Any]() // Updated line
attrs[NSAttributedStringKey.font] = codeFont
for style in styleList
{
if let themeStyle = themeDict[style]
{
for (attrName, attrValue) in themeStyle
{
attrs.updateValue(attrValue, forKey: attrName)
}
}
}
returnString = NSAttributedString(string: string, attributes:attrs )
}
以下是Apple的说明:NSAttributedString - Creating an NSAttributedString Object