At work, I code in either Java, Javascript (AngularJS, Node.js) or CSS via bootstrap, so when I am coding in Swift, it is strictly something I do in my free time. Hence I make a point to keep notes of stuff that I learn e.g. Optional types in Swift which can potentially serve as a future reference for me.

Optional types in Swift

Swift (Apple’s new programming language), allows for the presence optional type or optionals. This concept is very well explained in this Ray Wanderlich podcast, at time 27:03 (mins:secs). As mentioned in that podcast,  the designers of Swift decided to ensure that you have no null (nil) references in your code. So in languages such as Java, say you have an object called person which represents a person, that has information about where the person lives i.e. address property. There is some more detail in where the person lives i.e. the name of the street i.a. street property. So now if we want to what street the person lives on, you would do person.address.street. That way you trust the property address to never be null, by just calling person.addres.street. However there are instances when it does make sense for a certain property to be null and that is why optional types exist in Swift. So nullable (nillable) behaviour is something that you opt into. As pointed out in the podcast this is a very good safety feature.

References

This stackoverflow post has a very good answer with examples on the use of optional values in Swift. The official documentation is also a good place to read about how to use

Get updates?

If you find any of my posts useful and want to support me, you can buy me a coffee 🙂 https://www.buymeacoffee.com/bhumansoni Or you can  buying or even try one of my apps on the App Store.  https://mydaytodo.com/apps/ Also, if you can leave a review on the App Store or Google Play Store, that would help too.
Categories: iOSSwift

0 Comments

Leave a Reply

Avatar placeholder
Verified by MonsterInsights