【问题标题】:How to set an object as key in NSMutableDictionary in swift如何在 swift 中将对象设置为 NSMutableDictionary 中的键
【发布时间】:2016-02-20 15:13:09
【问题描述】:

我需要在 NSMutableDictionary 中设置一个对象作为键。我将我的字典声明为

var streamsDict : NSMutableDictionary = [:]

并将对象添加为

 streamsDict[stream] = "Value"

但由于我的应用程序崩溃而出现以下错误

Could not cast value of type 'OTStream' (0x100638590) to 'NSCopying' (0x19e0fb9e8)

我也试过

streamsDict[stream as! NSCopying] = "Value"

但我又遇到了错误

`Argument type 'OTStream' does not conform to expected type 'NSCopying'`

请推荐

【问题讨论】:

  • 你不能使用任何东西作为字典中的键,而且你不想......你想用字典实现什么?
  • 您设置为键的流变量类型是什么?
  • @Wain:我有 OTStream 对象,我需要将它们保存在具有某些值的字典中。之后,我可以获取该字典的 allKeys 数组以进一步执行我的任务。
  • @HarshalBhavsar:它是 OTStream 的一个对象。
  • 你不想那样做,解释一下你为什么要使用字典

标签: ios swift nsmutabledictionary


【解决方案1】:

只有符合NSCopying 的对象才能用作NSMutableDictionary 中的键。

如果您想将OTStream 对象用作字典中的键,您的NSCopying 对象必须实现NSCopying 协议。

您可以找到NSCopying 文档here。

【讨论】:

  • 感谢您的回答。但我收到以下错误Argument type 'OTStream' does not conform to expected type 'NSCopying'
  • 考虑将流设为可复制项是个坏主意
【解决方案2】:

可能你不直接将对象存储在字典中,而是首先将其所有属性序列化到 NSDictionary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多