0

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?

Matthew Quiros
  • 13,385
  • 12
  • 87
  • 132

2 Answers2

3

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.

Guido Hendriks
  • 5,706
  • 3
  • 27
  • 37
  • 1
    I would like to emphasize "this is not the good way". IUOs are very useful [in certain scenarios](http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals), but sprinkling them on optional variables is a fast path to crashes. – jtbandes Sep 10 '14 at 07:18
  • I think IUO's should be avoided when possible, except for certain cases. Don't believe this is one of those cases. – Guido Hendriks Sep 10 '14 at 07:22
2

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!

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Why did your variable suddenly become optional? Why wouldn't it matter to the rest of your code? These are the types of issues you should be thinking about (and with more practice, you'll see them earlier, and build them in ahead of time). – jtbandes Sep 10 '14 at 07:10
  • I'm storing an array in a variable. If it's nil, then my view controller hasn't retrieved data yet, so I must. Can't just check whether the size is 0 because it's a valid data count. – Matthew Quiros Sep 10 '14 at 07:13
  • 1
    This is obviously the recommended answer. Refactor or keep it this way. But there are rare cases in which implicitly unwrapped optionals are okay, but I don't think this is one. – Guido Hendriks Sep 10 '14 at 07:19