2017-02-24 72 views
1

我是swift的新手。 我想知道如何使用swift修改for-each循環中的對象。 例如:使用swift修改數組中的對象值

struct MyCustomObject {0} {0} {0} 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的數組];

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

是'myArray'一個'let'或'var'? –

+0

myArray是一個「讓」。 枚舉你的數組並改變數組元素使用索引<---不再是例子? –

+0

您是否希望更改永久保留在您的陣列中,還是希望它們只在循環中暫時存在? – Sven

回答

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" 
相關問題