loading...

How to easily configure properties in Swift

onmyway133 profile image Khoa Pham ・2 min read

This post lists the many ways that I know to easily configure properties in Swift

Using a helper method

var label: UILabel!

override func viewDidLoad() {
  super.viewDidLoad()

  configureLabel()
}

func configureLabel() {
  label = UILabel()
  label.backgroundColor = UIColor.greenColor()
  view.addSubview(label)
}

Using anonymous function

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

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

extension Then where Self: AnyObject {

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

so we have

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/

public func Init<Type>(value : Type, @noescape block: (object: Type) -> Void) -> Type
{
    block(object: value)
    return value
}

we can use it like

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

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

Posted on by:

onmyway133 profile

Khoa Pham

@onmyway133

My apps https://onmyway133.com/apps/

Discussion

pic
Editor guide