alfreedom
alfreedom

Reputation: 441

Duplicate custom object copying it by value not by reference

Which is the correct way to duplicate an object in swift 3?

I have an object

var element: Element!

Element is an ObjectMapper class

class Element: Mappable {

    var name = String()
    var description = String()
    var price = Float()
    var optionals = [Optional]()

    required init?(map: Map){
    }

    func mapping(map: Map) {

        name            <- map["n"]
        description     <- map["d"]
        price           <- map["p"]
        optionals       <- map["o"]
    }

}

I want to initialize element with some object of type Element and then create a tmpElement copied from element to modify tmpElement and leave element "untouched".

If I do

tmpElement = element

I think I am passing the reference so what I modify in tmpElement it will be modified in element too.

So which is the right way? I hope I explained myself...

Upvotes: 0

Views: 78

Answers (1)

shallowThought
shallowThought

Reputation: 19592

You can write an initializer that takes the Element to copy as an argument:

...
init(element:Element) {
     name = element.name
     description = element.description
     price = element.price
     optionals = element.optionals
}
...

and use it like this:

let element = Element(map)
let copy = Element(element)

Alternatively you could make Element a struct instead of a class.

Upvotes: 1

Related Questions