Contents
  1. 1. Using a helper method
  2. 2. Using anonymous function
  3. 3. @noescape configure Block on init
  4. 4. configure Block as extension
  5. 5. init without extension
  6. 6. anonymous function again

This post is like a sum up of sum ways to configure your property

Using a helper method
1
2
3
4
5
6
7
8
9
10
11
12
13
var label: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

configureLabel()
}

func configureLabel() {
label = UILabel()
label.backgroundColor = UIColor.greenColor()
view.addSubview(label)
}
Using anonymous function
1
2
3
4
5
lazy var label: UILabel = { [weak self] in
let label = UILabel()
label.backgroundColor = UIColor.greenColor()
return label
}()

Ah, by the way, did you know that

  • You shouldn’t call access label in ViewController deinit, because it is lazy and we have weak 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
2
3
public init(@noescape configBlock: (DependencyContainer->()) = { _ in }) {
configBlock(self)
}
configure Block as extension

This https://github.com/devxoul/Then makes it easier to configure your property as an extension to NSObject

1
2
3
4
5
6
7
extension Then where Self: AnyObject {

public func then(@noescape block: Self -> Void) -> Self {
block(self)
return self
}
}

so we have

1
2
3
lazy var label: UILabel = UILabel().then { [weak self] in
$0.backgroundColor = UIColor.greenColor()
}

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
2
3
4
5
public func Init<Type>(value : Type, @noescape block: (object: Type) -> Void) -> Type
{
block(object: value)
return value
}

we can use it like

1
2
3
lazy var label: UILabel = Init(UILabel()) { [weak self] in
$0.backgroundColor = UIColor.greenColor()
}

We have to declare label: UILabel to use `[weak self]

anonymous function again

This https://gist.github.com/erica/4fa60524d9b71bfa9819 makes configuration easier

1
2
3
4
lazy var label: UILabel = { [weak self] in
$0.backgroundColor = UIColor.greenColor()
return $0
}(UILabel())
Contents
  1. 1. Using a helper method
  2. 2. Using anonymous function
  3. 3. @noescape configure Block on init
  4. 4. configure Block as extension
  5. 5. init without extension
  6. 6. anonymous function again