swift tips

private(set) modifier

Sometimes there is a need to use or test some property outside the enclosing declaration (internal get).

At the same time, you don’t want this property to be modified outside – because, by applying good practices and for safety reasons, you want to protect against accidental, unauthorized change of properties from outside.

How to do it? It’s simple.

You can use the private (set) modifier, which means getter is internal and setter is private:

private(set) var someProperty

What if you want the property to be available outside the module (public get – if you’re creating the SDK, for example).

Then at the very beginning you need to add the public modifier:

public private(set) var someProperty

Leave a Reply

Your email address will not be published. Required fields are marked *