Sunday, June 28, 2015

Swift use of optionals

In learning swift the question mark or the exclamation point and when to use them can be confusing for the beginner. I found an article that really does a good job at explaining this point.
For example if those pieces of data represent an employee profile in a company database, for some records you might not know the height of the employee – in that case you shouldn’t set a value of 0 – you really should rather set the value to nothing or missing.


When you put a ! behind the property name you tell the compiler I don’t care that this property is optional, I know that when this code executes there always will be a value store so treat this Optional like a normal datatype. Well isn’t that nice? What would happen though if there isn’t a navigation controller to your view controller? If you suggestion that there always will be a value stored in navigationController was wrong? Your app will crash. Simple and ugly as that.

No comments:

Post a Comment