【问题标题】:Cannot convert value of type 'NSMutableArray' to expected argument type '[SKTexture]'无法将“NSMutableArray”类型的值转换为预期的参数类型“[SKTexture]”
【发布时间】:2016-05-05 17:22:01
【问题描述】:

我收到以下代码错误:

func prepareAnimationForDictionary(settings: NSDictionary,repeated: Bool) -> SKAction {
        let atlas: SKTextureAtlas = 
          SKTextureAtlas(named: settings["AtlasFileName"] as! String)
        let textureNames:NSArray = settings["Frames"] as! NSArray
        let texturePack: NSMutableArray = []

        for texPath in textureNames {
            texturePack.addObject(atlas.textureNamed(texPath as! String))
        }

        let timePerFrame: NSTimeInterval = Double(1.0/(settings["FPS"] 
         as! Float))

        let anim:SKAction = SKAction.animateWithTextures(texturePack, 
          timePerFrame: timePerFrame) // the error I get is here
        if repeated {
        return SKAction.repeatActionForever(anim)
        }else{
        return anim
        }

【问题讨论】:

标签: ios swift sprite-kit


【解决方案1】:

只需使用预期的 (Swift) 类型

...
let textureNames = settings["Frames"] as! [String]
var texturePack =  [SKTexture]()

for texPath in textureNames {
    texturePack.append(atlas.textureNamed(texPath))
}
...

从 Swift 的角度来看,可变 Foundation 集合类型 NSMutableArrayNSMutableDictionary 是未指定类型的,与 Swift 本机对应物无关。

【讨论】:

    【解决方案2】:

    更改timePerFrame(timePerFrame as [AnyObject]) as! [SKTexture]

    【讨论】:

      【解决方案3】:

      好的,考虑一下。你有一个变量texturePack。您没有显示声明,但根据错误消息,我将假设它的类型为 NSMutableArray。有问题的调用需要一个 SKTexture 对象数组。

      因此,请将您的 texturePack 转换为所需的类型:

      let anim:SKAction = SKAction.animateWithTextures(texturePack as! [SKTexture], 
        timePerFrame: timePerFrame) //error i get is here
      

      请注意,如果 texturePack 不是 SKTexture 对象的数组,您最好使用 if letguard 来检查转换是否成功:

      guard 
        let anim:SKAction = SKAction.animateWithTextures(texturePack as! [SKTexture], 
          timePerFrame: timePerFrame) //error i get is here
      else
      {
        return nil;
      }
      

      或者,正如其他人所建议的,将 texturePack 数组的声明更改为 [SKTexture] 类型

      【讨论】:

      • 这是正确的,但没有必要将texturePack 改为NSMutableArray 而不是快速的Array
      • 起初我没有在 OP 发布的代码中看到数组的声明,所以我认为数组是 NSMutableArray 而不是 Swift 类型数组可能是有正当理由的。如果您可以使数组成为 SKTexture 对象的 Swift 数组,那肯定会更好。 (或者就此而言,您可以使用新的类型化 NSArray 构造。)
      • 感谢大家的帮助。非常感谢
      猜你喜欢
      • 2016-03-26
      • 2016-07-27
      • 2016-07-02
      • 2016-03-21
      • 1970-01-01
      • 2020-03-01
      • 2016-08-01
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多