iosswift5

Best way / how to "touch" a lazy var?


Say you have some sort of lazy var, where you don't actually need the output

private lazy var setup: () = {
   ...
   ...
}()

another use case

private lazy var ball: UIView = {
   ...
}()
private lazy var bat: UIView = {
   ...
}()

, more efficient to group constraints in one activation

private lazy var gather: () = {
   NSLayoutConstraint.activate([
      .. all constraints for ball, bat etc
   ])
}()

How to touch the lazy var?

You can do this,

let _ = setup

no worries, but, what is the best syntax, the best way to "touch" a lazy var in Swift?

I never thought about this before!


Solution

  • A shorter (if that’s what you mean by “better”) way to do this is

    _ = dot
    

    This is the syntax you use to discard a value you don’t want. You’ve probably seen this used to discard the return value of a function call:

    _ = functionWithSideEffects()