denys
denys

Reputation: 2529

How to forbid object copying in swift3?

I want to be sure that every instance of the object is used by reference. Instantiated it could be several times but should not be copied.
F.e. in c++ it is easy to do:

class A {
public:
    A(const A&) = delete;
    A& operator = (const A&) = delete;
};

That is. Of course smbd could try to make some hack in memory - but it is not useful and not so easy. You should know exactly the memory layout of your object and all fields it encapsulates. I do not want smth special - just equivalent of the code above in swift 3.

Upvotes: 1

Views: 69

Answers (1)

Tommy
Tommy

Reputation: 100662

In Swift, classes are reference types. So they already do what you want: they can be held by reference only. They'll always be on the heap, and assignments will act to assign references, not class contents. So just make sure you declare your object as a class rather than a struct — unlike C++ the primary difference between the two in Swift is reference type versus value type.

Upvotes: 1

Related Questions