arrays - 如何改变数组中的变量?

标签 arrays swift

我正在尝试从我的数组中接收可变变量,但出了点问题。代码中的问题。

var baloonsArray = NSMutableArray()

override func didMoveToView(view: SKView) {
        var baloon = SKSpriteNode(imageNamed: "baloon") //"Variable "baloon" was never mutated; consider changing to "let" constant"
        baloon.xScale = 0.1
        baloon.yScale = 0.1

        ballonsArray.addObject(baloon)
        addChild(baloon)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {
        for var baloon in baloonsArray {
            baloon.xScale = 0.2 //Here xcode telling me: "Cannot assign to property: "ballon" is immutable". But i declared him as var. With Objective-C there was no problems. What should i do? 

        }
    }
}

当我尝试在 touchesBegan 函数中更改 baloon xScale 时,xcode 告诉我:“无法分配给属性:“ballon”是不可变的”。但我宣布他为 var。使用 Objective-C 没有问题。我应该怎么办?

最佳答案

问题是您对 NSMutableArray 的使用。对于 Swift 来说,它是不透明的。也就是说,Swift 不知道里面有什么。但是 Swift 有严格的类型。所以它不知道它的元素有什么属性,它不会让你分配给它不理解的属性。所以如果你真的想使用 NSMutableArray,你必须在获取它们时转换它的元素,这样 Swift 就知道它们是什么:

for baloon in baloonsArray {
    let baloonsprite = baloon as! SKSpriteNode
    baloonsprite.xScale = 0.2
}

行得通。但是,最好不要一开始就使用 NSMutableArray。相反,将 baloonsArray 声明为可变 Swift 数组:

var baloonsArray = [SKSpriteNode]()

这样可以更简洁地解决问题。现在 Swift 知道这个数组中有什么——它是 SKSpriteNode 对象。 Swift 知道可以分配给 SKSpriteNode 的 xScale

你需要习惯 Swift 的严格类型,包括数组元素是有类型的。

关于arrays - 如何改变数组中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957090/

相关文章:

ios - Swift 4 OutputStream 产生的输出多于输入

ios - iOS 上的 Realm : crash while creating nested object with primaryKey

ios - 如何在搜索栏上设置更改占位符颜色?

swift - 为什么这个 didSet 属性没有在 Swift 中打印任何输出?

JavaScript 为数组中不存在的键添加零

javascript - 在javascript中从数组中获取特定元素

python - 在 Python : Given an original array of numbers, 中,我将如何创建一个包含特定范围内原始数组值的新数组?

php - 将当前月份值与数组中前一个最后 5 个月的值相加

php - 始终使用值获取 $media

swift - 在 Firebase 中查询以下 AutoID