3

我在我的项目中使用下面的代码。更新到 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]?”

4

1 回答 1

9

在 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 - 创建一个 NSAttributedString 对象

于 2017-10-13T15:29:49.760 回答