DEV Community

Khoa Pham
Khoa Pham

Posted on

2 1

How to easily configure properties in Swift

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())

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay