Changing The value of struct in an array - arrays

I want to store structs inside an array, access and change the values of the struct in a for loop.
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'"
}
If I change the struct to class it works. Can anyone tell me how I can change the value of the struct.

Besides what said by #MikeS, remember that structs are value types. So in the for loop:
for test in testings {
a copy of an array element is assigned to the test variable. Any change you make on it is restricted to the test variable, without doing any actual change to the array elements. It works for classes because they are reference types, hence the reference and not the value is copied to the test variable.
The proper way to do that is by using a for by index:
for index in 0..<testings.count {
testings[index].value = 15
}
in this case you are accessing (and modifying) the actual struct element and not a copy of it.

Well I am going to update my answer for swift 3 compatibility.
When you are programming many you need to change some values of objects that are inside a collection. In this example we have an array of struct and given a condition we need to change the value of a specific object. This is a very common thing in any development day.
Instead of using an index to determine which object has to be modified I prefer to use an if condition, which IMHO is more common.
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)
Notice all the lets, this way of development is safer.
The classes are reference types, it's not needed to make a copy in order to change a value, like it happens with structs. Using the same example with classes:
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)

To simplify working with value types in arrays you could use following extension (Swift 3):
extension Array {
mutating func modifyForEach(_ body: (_ index: Index, _ element: inout Element) -> ()) {
for index in indices {
modifyElement(atIndex: index) { body(index, &$0) }
}
}
mutating func modifyElement(atIndex index: Index, _ modifyElement: (_ element: inout Element) -> ()) {
var element = self[index]
modifyElement(&element)
self[index] = element
}
}
Example usage:
testings.modifyElement(atIndex: 0) { $0.value = 99 }
testings.modifyForEach { $1.value *= 2 }
testings.modifyForEach { $1.value = $0 }

How to change Array of Structs
for every element:
itemsArray.indices.forEach { itemsArray[$0].someValue = newValue }
for specific element:
itemsArray.indices.filter { itemsArray[$0].propertyToCompare == true }
.forEach { itemsArray[$0].someValue = newValue }

You have enough of good answers. I'll just tackle the question from a more generic angle.
As another example to better understand value types and what it means they get copied:
struct Item {
var value:Int
}
func change (item: Item, with value: Int){
item.value = value // cannot assign to property: 'item' is a 'let' constant
}
That is because item is copied, when it comes in, it is immutable — as a convenience.
Had you made Item a class type then you were able to change its value.
var item2 = item1 // mutable COPY created
item2.value = 10
print(item2.value) // 10
print(item1.value) // 5

This is very tricky answer. I think, You should not do like this:
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)")
}
For Xcode 6.1, array initialization will be
var ary = [UnsafeMutablePointer<testing>](arrayLiteral: &test1, &test2)

It is possible to use the map function to get this effect - essentially creating a new array
itemsArray = itemsArray.map {
var card = $0
card.isDefault = aCard.token == token
return card
}

I ended up recreating a new array of struct see the example below.
func updateDefaultCreditCard(token: String) {
var updatedArray: [CreditCard] = []
for aCard in self.creditcards {
var card = aCard
card.isDefault = aCard.token == token
updatedArray.append(card)
}
self.creditcards = updatedArray
}

I tried Antonio's answer which seemed quite logical but to my surprise it does not work. Exploring this further I tried the following:
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

Related

Mutate Model Struct in a ForEach - Swift/SwiftUI [duplicate]

I am still not sure about the rules of struct copy or reference.
I want to mutate a struct object while iterating on it from an array:
For instance in this case I would like to change the background color
but the compiler is yelling at me
struct Options {
var backgroundColor = UIColor.blackColor()
}
var arrayOfMyStruct = [MyStruct]
...
for obj in arrayOfMyStruct {
obj.backgroundColor = UIColor.redColor() // ! get an error
}
struct are value types, thus in the for loop you are dealing with a copy.
Just as a test you might try this:
Swift 3:
struct Options {
var backgroundColor = UIColor.black
}
var arrayOfMyStruct = [Options]()
for (index, _) in arrayOfMyStruct.enumerated() {
arrayOfMyStruct[index].backgroundColor = UIColor.red
}
Swift 2:
struct Options {
var backgroundColor = UIColor.blackColor()
}
var arrayOfMyStruct = [Options]()
for (index, _) in enumerate(arrayOfMyStruct) {
arrayOfMyStruct[index].backgroundColor = UIColor.redColor()
}
Here you just enumerate the index, and access directly the value stored in the array.
Hope this helps.
You can use use Array.indices:
for index in arrayOfMyStruct.indices {
arrayOfMyStruct[index].backgroundColor = UIColor.red
}
You are working with struct objects which are copied to local variable when using for in loop. Also array is a struct object, so if you want to mutate all members of the array, you have to create modified copy of original array filled by modified copies of original objects.
arrayOfMyStruct = arrayOfMyStruct.map { obj in
var obj = obj
obj.backgroundColor = .red
return obj
}
It can be simplified by adding this Array extension.
Swift 4
extension Array {
mutating func mutateEach(by transform: (inout Element) throws -> Void) rethrows {
self = try map { el in
var el = el
try transform(&el)
return el
}
}
}
Usage
arrayOfMyStruct.mutateEach { obj in
obj.backgroundColor = .red
}
For Swift 3, use the enumerated() method.
For example:
for (index, _) in arrayOfMyStruct.enumerated() {
arrayOfMyStruct[index].backgroundColor = UIColor.redColor()
}
The tuple also includes a copy of the object, so you could use for (index, object) instead to get to the object directly, but since it's a copy you would not be able to mutate the array in this way, and should use the index to do so. To directly quote the documentation:
If you need the integer index of each item as well as its value, use
the enumerated() method to iterate over the array instead. For each
item in the array, the enumerated() method returns a tuple composed of
an integer and the item.
Another way not to write subscript expression every time.
struct Options {
var backgroundColor = UIColor.black
}
var arrayOfMyStruct = [Options(), Options(), Options()]
for index in arrayOfMyStruct.indices {
var option: Options {
get { arrayOfMyStruct[index] }
set { arrayOfMyStruct[index] = newValue }
}
option.backgroundColor = .red
}
I saw this method in some code and it seems to be working
for (var mutableStruct) in arrayOfMyStruct {
mutableStruct.backgroundColor = UIColor.redColor()
}

Can't access a specific Struct in an array on swift. Keep getting this error "Cannot call value of non-function type '""

I am trying to read and/or console print on of the elements of my array which consist of 28 structs. I can not access any of the struct on my array is says that "Cannot call value of non-function type '[Ficha]'" and I can't find why.. Sorry kind of a newbie on swift.. The section commented is where I discovered the problem but I can't even print one of the elements.
Please help
import UIKit
import Foundation
struct Ficha {
var numero: Int
var ladoA = 0
var ladoB = 0
}
extension Ficha: CustomStringConvertible {
var description: String {
return "f\(numero) \(ladoA)/\(ladoB)"
}
}
var dSet = [Ficha] ()
var rSet = [Int: Ficha] ()
func setDset () {
dSet = []
rSet = [:]
var fj = 0
var x1: Double = 0
var ficha1 : Ficha
var fichanum = 0
for x in 0...6 {
for y in x...6 {
fichanum = fichanum + 1
dSet.append(Ficha.init(numero: fichanum, ladoA: x, ladoB: y))
}
}
dSet.shuffle()
}
setDset()
print (dSet(2))
Using dSet with parenthesis is incorrect, that's the syntax for a function. So the line:
print(dSet(2))
is assuming there's a function that returns something:
func dSet(_ x: Int) -> Something {
return Something
}
To access an item at an index you use the square brackets, so it should be:
print(dSet[2])
Which will print the item at index 2 in the array dSet.
As others have pointed out, you access members of a collection using subscripts, which are invoked via [], not () (which is for regular function calls).
You can simplify this code quite a bit, btw:
import UIKit
struct Ficha {
var numero: Int
var ladoA = 0
var ladoB = 0
}
extension Ficha: CustomStringConvertible {
var description: String {
return "f\(numero) \(ladoA)/\(ladoB)"
}
}
func calculateDset() -> [Ficha] {
let xyPairs = (0...6).flatMap { x in
(x...6).map { y in (x: x, y: y) }
}
return zip(1..., xyPairs)
.map { (fichanum, pair) in
return Ficha(numero: fichanum, ladoA: pair.x, ladoB: pair.y)
}
.shuffled()
}
let dSet = calculateDset()
print(dSet[2])
UIKit already imports Foundation
Make functions return values, don't set them directly.
Don't set initial values to variables, only to immediate overwrite them with something else.
rSet, fj, x1, and ficha1 are unused, delete them.

Get struct properties from string - swift

I declared a struct with 4 properties ( informationA, informationB, informationC, informationD ).
Also I've declared an array like this (The array includes some names of the my_struct properties as "strings" :
let keys = ["informationA", "informationB", "informationC"]
Now I'd like a for-loop to go through the "keys"-array and print out the struct property values for the current string ("informationA", "informationB", "informationC").
struct my_struct {
var informationA = "test"
var informationB = "test...test"
var informationC = "test...test"
var informationD = "test...test..."
}
func getInformation() {
let keys = ["informationA", "informationB", "informationC"]
for i in keys {
print(my_struct.i) // ERROR: Type 'my_struct' has no member 'i'
// should print ---> "test", "test...test", "test...test"
}
}
Using the code from above I'm getting this error ERROR: Type 'my_struct' has no member 'i'.
Is there a way to avoid this message and achieve the result I'd like to get?
What you are looking for is reflection:
struct MyStruct {
var informationA = "test"
var informationB = "test...test"
var informationC = "test...test"
var informationD = "test...test..."
}
func getInformation() {
let my_struct = MyStruct()
let keys = ["informationA", "informationB", "informationC"]
let m = Mirror(reflecting: my_struct)
let properties = Array(m.children)
for k in keys {
if let prop = properties.first(where: { $0.label == k }) {
print(prop.value)
}
}
}

Find element in an array of object

I created an array of objects:
var fullMonthlyList = [SimulationMonthly]()
The class here:
class SimulationMonthly {
var monthlyMonthDuration: NSNumber = 0
var monthlyYearDuration: NSNumber = 0
var monthlyFullAmount: NSNumber = 0
var monthlyAmount: Int = 0
init(monthlyMonthDuration: NSNumber, monthlyYearDuration: NSNumber, monthlyFullAmount: NSNumber, monthlyAmount: Int){
self.monthlyMonthDuration = monthlyMonthDuration
self.monthlyYearDuration = monthlyYearDuration
self.monthlyFullAmount = monthlyFullAmount
self.monthlyAmount = monthlyAmount
}
}
I just did append to populate it, now I want to find for example if they're an existing value, for example monthlyAmount equals to "194" by search in the array, how can I do ? I have tried filter and contains but I get errors.
What I've tried:
if self.fullMonthlyList.filter({ $0.monthlyAmount == self.monthlyAmount.intValue }) { ... }
Error:
Cannot invoke 'filter' with an argument list of type '((SimulationMonthly) throws -> Bool)'
You can do:
if let sim = fullMonthlyList.first(where: { $0.monthlyAmount == 194 }) {
// Do something with sim or print that the object exists...
}
This will give you the first element in your array where monthlyAmount equals 194.
If you want all elements with that condition, you can use filter:
let result = fullMonthlyList.filter { $0.monthlyAmount == 194 }
If you don't need the object at all but you just want to know if one exists, then contains would be enough:
let result = fullMonthlyList.contains(where: { $0.monthlyAmount == 194 })
Here's a simple playground example of filtering objects based on matching a property. You should be able to expand it to your situation.
class Item {
var value: Int
init(_ val: Int) {
value = val
}
}
var items = [Item]()
for setting in 0..<5 {
items.append(Item(setting))
}
func select(_ with: Int) -> [Item] {
return items.filter { $0.value == with }
}
let found = select(3)

Swift Any Array not accessing Struct Methods

So, I have the following code in Swift 2:
struct IntToken {
var value:Int
init(val:Int) {
self.value = val
}
mutating func add(val:IntToken) {
self.value += val.value
}
}
var table = [Any]()
table.append(IntToken(val:3))
table.append(IntToken(val:4))
table[0].add(table[1])
This gives me the following error
Playground execution failed: /var/folders/jx/bhltcyc90117d2wx_r82p4fr0000gn/T/./lldb/73237/playground71.swift:22:6: error: value of type 'Any' (aka 'protocol<>') has no member 'add'
table[0].add(table[1])
~~~~~^~~ ~~~
The issue is, I am trying to create an Array, that will contain different type of objects, not just IntToken's, but I also want to be able to access the elements of that array and use their methods on one another. Whenever I try to use the Any array, however, it doesn't allow me to do this, because it's reading the accessed struct instance as an any type.
What's a good way to accomplish what I am trying to do?
Starting with your original struct:
struct IntToken {
var value:Int
init(val:Int) {
self.value = val
}
mutating func add(val:IntToken) {
self.value += val.value
}
}
Do like this:
var table = [Any]()
table.append(IntToken(val:3))
table.append(IntToken(val:4))
var it = table[0] as! IntToken // take it out with cast and var ref
it.add(table[1] as! IntToken) // add with cast; `it` is now IntToken(val:7)
table[0] = it // put it back in (if you want to)
i slightly modified matt's answer (accepted answer) to show how to avoid crash in case some table element has other type as IntToken.
var table:[Any] = []
table.append(IntToken(val:3))
table.append(IntToken(val:4))
if let it0 = table[0] as? IntToken,
let it1 = table[1] as? IntToken {
var it0 = it0
it0.add(it1)
table[0] = it0
}
print(table) // [IntToken(value: 7), IntToken(value: 4)]
I prefer to modify your IntToken
struct IntToken {
var value:Int
func add1(token: IntToken)->IntToken {
var token = token
token.value += value
return token
}
}
and remove any 'mutating' function from it. Now the original code snippet could be modified to 'more functional' and easy to understand version
var table = [Any]()
table.append(IntToken(value:3))
table.append(IntToken(value:4))
if let it1 = table[1] as? IntToken,
let v = (table[0] as? IntToken)?.add1(it1) {
table[0] = v
}
print(table) // [IntToken(value: 7), IntToken(value: 4)]

Resources