Optional("Working as intended")

As mentioned in a previous post, I've been working on an iOS app over the holidays. A topic for another post is all of the hassle with getting to the point where I can actually release it for sale, but while I've been sorting all that out I've been noodling around with new features to keep myself interested (although going back to work has gotten in the way ever so slightly). 

One of the features that has taken some time to get my head around in Swift is optionals, where a value can be nil or the optional value of whatever type it is supposed to be. Optionals make for some nice control flow schemes, and XCode is pretty good about warning you when you are doing the wrong thing with them.


If you have an optional which you are using as part of a string (like me - I was using them to store image names and loading a place holder image if they were not set) you can get some weird behavior. When an optional is set and used to compose a string through Swift's string formatting, things can get ugly:

e.g. "/path/to/file/\(fileName) "

If fileName is an optional, then when that filename is set, it will be rendered as 'Optional("some file")' rather than just 'some file', which, when you are then later on checking for whether or not the file exists, can be a bit confusing. The image file gets displayed fine, so the camera code is fine, it's written without an error, but later on isn't loaded. Of course what is happening is the file is getting written as the 'Optional' file name, and then looked for without the optional wrapping.

Fun times.