This article is also published on my blog.
Sometimes, you need to do more than just assign a value to a property on initialization.
class Foo { let formatter = DateFormatter() }
You might need to configure some of the properties. The first thing that comes to your mind is probably doing it in an initializer.
class Foo { let formatter = DateFormatter() init() { formatter.dateStyle = .short } }
There are more ways how to configure your properties without putting the code in the initializer.
class Foo { let formatter: DateFormatter = { $0.dateStyle = .short return $0 }(DateFormatter()) }
In the example above, you can see that the property Foo.formatter
is constructed with a closure which takes the instance of DateFormatter
as a parameter. You can do the same with initializing the DateFormatter
directly in the closure:
class Foo { let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short return formatter }() }
You can also use a function or a static method to construct the property.
func dateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .short return formatter } class Foo { let formatter: DateFormatter = dateFormatter() }
class Foo { let formatter: DateFormatter = Foo.dateFormatter() static func dateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .short return formatter } }
All these options work for local variables too.
Get in touch on Twitter @zdnkt for comments, discussion feedback or ideas!
This article is also published on my blog.
Top comments (0)