Swift Lesson of the Day: Properties Aren't Sacred

While working on some swift code, I learned a few things today. Things like computed properties are not lazy properties (that one stung). I also started to realize that in Swift, properties aren't sacred. In Objective C they must be declared and synthesized and initialized. There are implicit methods behind setting and getting that you have to understand. In Swift they're just variables. And if you treat them like Objective C properties you're going to have a bad time.

For one, if they're not optional, they must be given a value in your overridden init method before calling super. Or, if you're subclassing UIView or UIViewController, possibly two init methods. The rules for accessing self are strict here too so trying to bury this setup in a function can be problematic. If you're building a UIView subclass that needs to set up a mess of subviews this can get old really quick. Best option I've found so far? Just initialize them with a default value like you would a regular variable. Now the compiler's off your back and and you can move on with your life, or at least what's left of it after choosing software development as a career.

"Swift Lesson of the Day: Properties Aren't Sacred" was originally published on 10 Aug 2014.