【问题标题】:How can I define type within a NSArray如何在 NSArray 中定义类型
【发布时间】:2014-09-14 19:47:49
【问题描述】:

在 NSDictionary 对象的 NSArray 中给出“结果”

我怎样才能删除临时常量r的需要:

for result in results {
    let r :NSDictionary = result as NSDictionary
    println(r.valueForKey("heading"))
}

【问题讨论】:

  • 我不知道,for result: NSDictionary in results 有效吗?
  • @GradyPlayer 类型注释与上下文类型“AnyObject”不匹配
  • 我想值得一试。
  • 结果数组的类型到底是什么?是[NSDictionary]吗?你能展示它的声明吗?

标签: swift syntactic-sugar


【解决方案1】:

类型推断来救援。显式键入结果“作为 NSDictionary”应该可以工作,但类型推断已经知道循环迭代器是 NSDictionary。以下代码将正确输出“value1”和“value2”。

var results = [NSDictionary]()
results.append(["heading": "value1", "anotherKey": "anotherValue1"])
results.append(["heading": "value2", "anotherKey": "anotherValue1"])

for result in results {
    println(result.valueForKey("heading"))
}

【讨论】:

  • 当然,我的记忆声称已经先尝试过这个......但是是的,它有效!谢谢。我确实尝试过“as NSDictionary”,但编译器对在“for result”之后和“in results {”之前添加它不满意
  • 在 for 循环中强制转换的语法是 for element in collection as CollectionTypefor element:ElementType in collection,而不是 for element as ElementType in collection
猜你喜欢
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 2018-02-23
相关资源
最近更新 更多