【问题标题】:Swift. How do i get the type of node.children?迅速。我如何获得 node.children 的类型?
【发布时间】:2016-12-24 00:49:00
【问题描述】:

我有这个作为我的代码:

for child in viewsArray[i].children {
    let childNode = child as! SKSpriteNode
    if childNode.color == UIColor.blackColor() && childNode.alpha == 1 {
        childNode.alpha = 0.5
    }
}

它给了我这个错误:

无法将“SKCropNode”(0x1a04415a0) 类型的值转换为“SKSpriteNode”(0x1a0441230)。

所以我的问题是在我写let childNode = child as! SKSpriteNode之前如何检查孩子的类型,这样我才能避免这个错误?

【问题讨论】:

    标签: swift types sprite-kit children skspritenode


    【解决方案1】:

    如果你想使用函数式编程,这里是代码

    viewsArray[i].children
        .flatMap { $0 as? SKSpriteNode }
        .filter { $0.color == .blackColor() && $0.alpha == 1 }
        .forEach { $0.alpha = 0.5 }
    

    【讨论】:

      【解决方案2】:

      怎么样:

      for child in viewsArray[i].children {
          guard let childNode = child as? SKSpriteNode else { continue }
          if childNode.color == UIColor.blackColor() && childNode.alpha == 1 {
              childNode.alpha = 0.5
          }
      } 
      

      【讨论】:

      • 哦,会的!请参阅文档! “guard 语句的 else 子句是必需的,并且必须调用标有 noreturn 属性的函数,或者使用以下语句之一将程序控制转移到 guard 语句的封闭范围之外:return、break、continue、throw”。 developer.apple.com/library/ios/documentation/Swift/Conceptual/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多