Property configuration in Swift
Contents
This post is like a sum up of sum ways to configure your property
Using a helper method
1 |
var label: UILabel! |
Using anonymous function
1 |
lazy var label: UILabel = { [weak self] in |
Ah, by the way, did you know that
- You shouldn’t call access
label
in ViewControllerdeinit
, because it islazy
and we haveweak self
-
lazy
increases your compile time
@noescape configure Block on init
I first saw it on https://github.com/AliSoftware/Dip/blob/develop/Sources/Dip.swift#L61
1 |
public init( configBlock: (DependencyContainer->()) = { _ in }) { |
configure Block as extension
This https://github.com/devxoul/Then makes it easier to configure your property as an extension to NSObject
1 |
extension Then where Self: AnyObject { |
so we have
1 |
lazy var label: UILabel = UILabel().then { [weak self] in |
We have to declare label: UILabel
to use `[weak self]
init without extension
I try to avoid extension, after reading this http://nshipster.com/new-years-2016/
1 |
public func Init |
we can use it like
1 |
lazy var label: UILabel = Init(UILabel()) { [weak self] in |
We have to declare label: UILabel
to use `[weak self]
anonymous function again
This https://gist.github.com/erica/4fa60524d9b71bfa9819 makes configuration easier
1 |
lazy var label: UILabel = { [weak self] in |