2

I have a struct and a class:

class FooClass {
    var someValue: String = "123"
}
struct TestStruct {
    var aValue: Int = 12
    var clsValue: FooClass
}

And I want a deep copy for TestStruct, but the following code will also change clsValue in variable a:

var a = TestStruct(aValue: 10, clsValue: FooClass())
var b = a
b.clsValue.someValue = "abc"

I know the class value in the struct is copied only 'reference', but I want a deep copy for this class when I assigning a to b.

I do know c++ can define a copy constructor or override the = operator. Does Swift support something like that?

1 Answer 1

1

A copy constructor is nothing more than an initializer that takes another instance of the same type. Simply define such initializers for your class and struct with the appropriate deep copies.

class FooClass {
    var someValue: String = "123"

    init() {
    }

    init(someValue: String) {
        self.someValue = someValue
    }

    // "Copy constructor"
    convenience init(_ other: FooClass) {
        self.init(someValue: other.someValue)
    }
}

struct TestStruct {
    var aValue: Int = 12
    var clsValue: FooClass

    init(aValue: Int, clsValue: FooClass) {
        self.aValue = aValue
        self.clsValue = FooClass(clsValue) // deep copy
    }

    // "Copy constructor"
    init(_ other: TestStruct) {
        self.init(aValue: other.aValue, clsValue: other.clsValue)
    }
}

var a = TestStruct(aValue: 10, clsValue: FooClass())
var b = TestStruct(a) // create new instance with its deep copy
b.clsValue.someValue = "abc"
print(a.clsValue.someValue) // prints 123
Sign up to request clarification or add additional context in comments.

2 Comments

I know that would work. But you should manually write this code 'var b = TestStruct(a)'. Can I just use 'var b = a' to do the deep copy work?
@NewSelf No, since you can't redefine the = operator to call your "copy constructor" initializer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.