arrays - puntatori - array bidimensionale dinamico c++
Modifica del valore di struct in un array (5)
Bene, aggiornerò la mia risposta per la rapida compatibilità con 3.
Quando si programmano molti è necessario modificare alcuni valori degli oggetti che si trovano all'interno di una raccolta. In questo esempio abbiamo una matrice di struct e data una condizione dobbiamo cambiare il valore di un oggetto specifico. Questa è una cosa molto comune in ogni giorno di sviluppo.
Invece di usare un indice per determinare quale oggetto debba essere modificato, preferisco usare una condizione if, che IMHO è più comune.
import Foundation
struct MyStruct: CustomDebugStringConvertible {
var myValue:Int
var debugDescription: String {
return "struct is \(myValue)"
}
}
let struct1 = MyStruct(myValue: 1)
let struct2 = MyStruct(myValue: 2)
let structArray = [struct1, struct2]
let newStructArray = structArray.map({ (myStruct) -> MyStruct in
// You can check anything like:
if myStruct.myValue == 1 {
var modified = myStruct
modified.myValue = 400
return modified
} else {
return myStruct
}
})
debugPrint(newStructArray)
Notate tutte le possibilità, questo modo di sviluppo è più sicuro.
Le classi sono tipi di riferimento, non è necessario creare una copia per modificare un valore, come succede con le strutture. Usando lo stesso esempio con le classi:
class MyClass: CustomDebugStringConvertible {
var myValue:Int
init(myValue: Int){
self.myValue = myValue
}
var debugDescription: String {
return "class is \(myValue)"
}
}
let class1 = MyClass(myValue: 1)
let class2 = MyClass(myValue: 2)
let classArray = [class1, class2]
let newClassArray = classArray.map({ (myClass) -> MyClass in
// You can check anything like:
if myClass.myValue == 1 {
myClass.myValue = 400
}
return myClass
})
debugPrint(newClassArray)
https://src-bin.com
Voglio memorizzare le strutture all'interno di un array, accedere e modificare i valori della struttura in un ciclo for.
struct testing {
var value:Int
}
var test1 = testing(value: 6 )
test1.value = 2
// this works with no issue
var test2 = testing(value: 12 )
var testings = [ test1, test2 ]
for test in testings{
test.value = 3
// here I get the error:"Can not assign to 'value' in 'test'"
}
Se cambio la struttura in classe funziona. Qualcuno può dirmi come posso cambiare il valore della struttura.
Answer #1
Hai abbastanza di buone risposte. Mi limiterò ad affrontare la questione da un punto di vista più generico.
Come altro esempio per capire meglio i tipi di valore e cosa significa che vengono copiati:
struct Item {
var value:Int
}
var item1 = Item(value: 5)
func testMutation ( item: Item){
item.value = 10 // cannot assign to property: 'item' is a 'let' constant
}
Questo perché l'oggetto è copiato, quando entra, è immutabile - per comodità.
func anotherTest (item : Item){
print(item.value)
}
anotherTest(item: item1) // 5
Nessuna mutazione accade quindi nessun errore
var item2 = item1 // mutable copy created.
item2.value = 10
print(item2.value) // 10
print(item1.value) // 5
Answer #2
Ho provato la risposta di Antonio che sembrava abbastanza logica, ma con mia sorpresa non funziona. Esplorando ulteriormente, ho provato quanto segue:
struct testing {
var value:Int
}
var test1 = testing(value: 6 )
var test2 = testing(value: 12 )
var testings = [ test1, test2 ]
var test1b = testings[0]
test1b.value = 13
// I would assume this is same as test1, but it is not test1.value is still 6
// even trying
testings[0].value = 23
// still the value of test1 did not change.
// so I think the only way is to change the whole of test1
test1 = test1b
Answer #3
Oltre a quanto detto da @MikeS, ricorda che le strutture sono tipi di valore. Quindi nel ciclo for
:
for test in testings {
una copia di un elemento dell'array viene assegnata alla variabile di test
. Qualsiasi modifica apportata su di essa è limitata alla variabile di test
, senza apportare alcuna modifica effettiva agli elementi dell'array. Funziona per le classi perché sono tipi di riferimento, quindi il riferimento e non il valore viene copiato nella variabile di test
.
Il modo corretto per farlo è usando un indice for
:
for index in 0..<testings.count {
testings[index].value = 15
}
in questo caso stai accedendo (e modificando) l'effettivo elemento struct e non una copia di esso.
Answer #4
Questa è una risposta molto difficile. Penso che non dovresti fare così :
struct testing {
var value:Int
}
var test1 = testing(value: 6)
var test2 = testing(value: 12)
var ary = [UnsafeMutablePointer<testing>].convertFromArrayLiteral(&test1, &test2)
for p in ary {
p.memory.value = 3
}
if test1.value == test2.value {
println("value: \(test1.value)")
}
Per Xcode 6.1, l'inizializzazione dell'array sarà
var ary = [UnsafeMutablePointer<testing>](arrayLiteral: &test1, &test2)