首页 文章

使用swift [duplicate]修改数组中的对象值

提问于
浏览
4

这个问题在这里已有答案:

我是新手 . 我想知道如何使用swift修改for-each循环中的对象 . 例如:

struct MyCustomObject {var customValue:String? }

让myArray:[MyCustomObject?]

for anObject:MyCustomObject in myArray {
    anObject.customValue = "Hello" // <---Cannot assign to property: 'anObject' is a 'let' constant 
}

那么,如果我想在for循环中更改对象值,该怎么办?我厌倦了在anObject之前添加“var”,但它不起作用!! (数组中的对象仍然保持不变 . )

对于目标C,它很容易,

NSMutableArray * myArray = [NSMutableArray array];

for (MyCustomObject * object in myArray) 
{ 
  object.customValue = "Hello" 
}

2 回答

  • 5

    那是因为存储在数组中的值是不可变的 . 你有2个选择:

    1:将 MyCustomObject 更改为一个类:

    class MyCustomObject { var customValue: String? }
    

    2:按索引迭代

    for i in 0..<myArray.count {
        if myArray[i] != nil {
            myArray[i]!.customValue = "Hello"
        }
    }
    
  • 0
    let temObj:MyCustomObject  = anObject  
     temObj.customValue = "Hello"
    

相关问题