Xin Lok
Xin Lok

Reputation: 529

Adding new element to Array - Swift 3

I have a Tableviewcontroller BeamsNameVC with 2 variables: Name and number. If for example, the number is 7, and if I click on any row in this View controller, it will segue to another TableViewcontroller SpansListVC and than it will show 7 rows: S1, S2, S3, S4, S5, S6 & S7.

I want to save these Data, so I created 2 swift files:

class StructureElement: NSObject, NSCoding {

var name = ""
var nbrSpans = ""
var spans = [LoadDetailsForEachSpan]()

and

class LoadDetailsForEachSpan: NSObject, NSCoding {

var i_SpanName = ""
var i_Spanlength = ""
var i_ConcentratedLoadForEachSpans = [ConcentratedLoadForEachSpan]()

I created a protocol with the following:

let spanNbr = Int(structureElement[newRowIndex].nbrSpans)
let newElementDetailSpan = LoadDetailsForEachSpan()
    for i in 0...spanNbr! {
        newElementDetailSpan.i_SpanName = "S" + " \(i)"
        structureElement[newRowIndex].spans.append(newElementDetailSpan)
    }

If i run the application, it will segue to * SpansListVC* but all values are the last i.

Example:

if name is Test 7 and number of span is 7, I will be having inside *[Spans] * 7 values with the same name:

spans[0] = S 7  
spans[1] = S 7  
....

Any mistake with above code?

Upvotes: 0

Views: 237

Answers (2)

Xin Lok
Xin Lok

Reputation: 529

Thanks @thm for your reply.

however, i find another solution as follow and it works:

    var spanDetailAndLoadItem: [SpanDetailsAndLoads] = []

    for var i in 1...nbr! {
        let item = SpanDetailsAndLoads(name: "S\(i) - S\(i + 1)")
        spanDetailAndLoadItem.append(item)
    }
    self.spans = spanDetailAndLoadItem

Upvotes: 0

thm
thm

Reputation: 1227

Welcome to the hell that mutable data objects can be ;). You are creating a single LoadDetailsForEachSpan instance and add that same instance a number of times to the array, while setting the i_SpanName property of that same instance every time the loop is iterated. You probably want to pull the instance creation into the loop:

for i in 0...spanNbr! {
    let newElementDetailSpan = LoadDetailsForEachSpan()
    newElementDetailSpan.i_SpanName = "S" + " \(i)"
    structureElement[newRowIndex].spans.append(newElementDetailSpan)
}

Upvotes: 1

Related Questions