MLQ
MLQ

Reputation: 13511

Changing non-optional variable to Swift optional type breaks all its occurrences in code

I have an instance variable that's not declared as an optional type in Swift (it always has an initial value).

var array: Array<MyObject> = []

Later in my project I realized I should make it an optional:

var array: Array<MyObject>?

When I do this, however, it breaks all occurrences of the variable in the current code. I suddenly have to append a ? to every time it is invoked.

Is there a way of writing variables in Swift such that its occurrences do not break when you toggle between making it optional and non-optional?

Upvotes: 0

Views: 358

Answers (2)

Guido Hendriks
Guido Hendriks

Reputation: 5776

If you don't want to make it a real optional, but it needs to be nil, you can make it an implicitly unwrapped optional. You declare one like this:

var foo: String!

Then you can just use it like you do now, but it can be nil as well. You should only use it without a nil-check if you're really sure you did actually set it.

But this is not the good way, since you lose the safety which Swift provides for optionals. I can still only recommend refactoring to an optional, but if that's not possible this should do the trick.

For more info about implicitly unwrapped optionals, I would like to refer to the chapters "The Basics" and "Automatic Reference Counting" in "The Swift Programming Language" iBook by Apple.

Upvotes: 3

jtbandes
jtbandes

Reputation: 118671

Not really, no.
(You might be able to get away with some refactoring features of Xcode, like Rename All in Scope.)

But this is actually a good thing! If you realize that a variable needs to be optional, well, the rest of your code must realize it too, and handle it appropriately. In Swift, this is enforced.

Enjoy writing safer code!

Upvotes: 2

Related Questions