Swift 无法为类型为';[字符串:AnyObject]';索引类型为';NSAttributedStringKey';
我在我的项目中使用以下代码。更新到swift 4后,我发现了错误。我怎样才能修好它 代码:Swift 无法为类型为';[字符串:AnyObject]';索引类型为';NSAttributedStringKey';,swift,nsattributedstring,xcode9,swift4,nsattributedstringkey,Swift,Nsattributedstring,Xcode9,Swift4,Nsattributedstringkey,我在我的项目中使用以下代码。更新到swift 4后,我发现了错误。我怎样才能修好它 代码: let returnString : NSAttributedString if styleList.count > 0 { var attrs = [String:AnyObject]() attrs[NSAttributedStringKey.font] = codeFont for style in styleList {
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]”
在swift 4中,NSAttributed字符串表示法完全改变 将属性字典
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的注释:属性的类型应该是[NSAttributedStringKey:Any],而不是[String:AnyObject]。为了给出解释:
NSAttributedString
不是人们可能认为的NSString
的子类。@RamyAlZuhouri很好地工作,谢谢,如果styleList.count>0,则不检查,如果不是空的,则测试!styleList.isEmpty
如果你像@RamyAlZuhouri所说的那样定义属性类型[NSAttributedStringKey:Any]
,那么就不需要使用attrs[NSAttributedStringKey.font]=codeFont
只需传递caseattrs[.font]=codeFont
谢谢……这对我很有效。。。