【发布时间】:2017-10-13 12:55:13
【问题描述】:
我在我的项目中使用以下代码。更新到 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]?”
【问题讨论】:
-
属性应该是 [NSAttributedStringKey : Any] 类型,而不是 [String:AnyObject]。
-
解释一下:
NSAttributedString并不是大家想象的NSString的子类。 -
@RamyAlZuhouri 工作正常,谢谢
-
并且不检查
if styleList.count > 0测试是否不为空!styleList.isEmpty -
如果你定义你的 attrs 类型
[NSAttributedStringKey: Any]为 @RamyAlZuhouri 说没有必要使用attrs[NSAttributedStringKey.font] = codeFont只是通过案例attrs[.font] = codeFont
标签: swift nsattributedstring xcode9 swift4 nsattributedstringkey