【问题标题】:Cannot subscript a value of type '[String : AnyObject]' with an index of type 'NSAttributedStringKey' [duplicate]无法使用“NSAttributedStringKey”类型的索引为“[String:AnyObject]”类型的值下标 [重复]
【发布时间】: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


【解决方案1】:

在 swift 4 - NSAttributedString 表示完全改变了。

[NSAttributedStringKey:Any]替换你的属性字典attrs类型[String:AnyObject]

试试这个:

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

【讨论】:

  • 谢谢...它对我有用...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 2020-02-08
  • 2016-11-04
相关资源
最近更新 更多