Swift 4 Array get reference

Good day everybody,

I run into an issue with arrays in swift, the problem is that it's a value type in swift. I'm trying to find a workaround. Here is the code that I have:


class Object: Codable{
    var name : String?
}

var objects: Array<Object>?
objects = Array<Object>()
if var obj = objects { // <----- Creates a copy of array here
    let o = Object()
    o.name = "1"
    objects?.append(o)
    print(obj) //<----- this one is missing "o" object
    print(objects)
}


I cannot use NSMutableArray because I have an array inside another codable class.

What's everybody's experience on this one? If somebody can share a solutions for that. Thanks!

Replies

I tried this to pass by reference. Seem to work (with limited testing)


class NewObject: Codable {
    var name : String?
}

class NewObjectArray {
    var theArray: [NewObject]?
}

var objects : NewObjectArray? = NewObjectArray() // Array?
objects!.theArray = []
if let obj = objects { // <----- Creates a copy of array here
     let o = NewObject()
    o.name = "First"
    objects!.theArray!.append(o)
     print(obj.theArray!.count) //<----- this one is missing "o" object
    print(objects!.theArray!.count)
}