How to insure lazy var instantiated in init()?

I'm using a common pattern to lazily create a var:

private lazy var peripheralManager: CBPeripheralManager = { CBPeripheralManager(delegate: self, queue: self.queue, options: nil) }()
init?(uuid: NSUUID, major: Int, minor: Int) {
  ...
  super.init()

  peripheralManager.isAdvertising // has no affect, but will insure we instantiate peripheralManager


I haven't actually tested the above - I was doing peripheralManager.startAdvertising() but that's the wrong thing to do at this point for this class.


What I have there - retrieving the value of a class var - seems fragile. The optimizer could (in the future if it doesn't now) determine that calling this var has no side effects, and since its not use just remove the statement.


So I'm sort of stuck - I can make the var la forced unwrapped optional, or I can call some method that I know will fail hoping it doesn't introduce side effects to that object.


Suggestions?

Why must it be lazy?

Try as I might with using "let", there is no way I can get this to compile otherwise. Note the "self" and "self.queue" in the parameter list.


My understanding in Swift 1.x, that you could use a closure to do this in conjunction with "lazy var" - I saw this earlier and have used it with great success in other code. It's just that in this case there is no method I can call that isn't just silly or obviously something that cannot have any affect (like calling "stopAdvertising()".


If I don't "get it", I'm all ears on how to properly construct this object.

I don't have an easy way to test this, but since CBPeripheralManager seems able to take nil for the delegate and queue, would this work?

    let  peripheralManager = CBPeripheralManager(delegate: nil, queue: nil, options: nil)
    init?(uuid: NSUUID, major: Int, minor: Int)
    {
        /* ... */
        super.init()
    
        peripheralManager.delegate = self
        peripheralManager.queue = self.queue

    }

You could make peripheralManager an implicitly unwrapped optional. I am fairly certain this is one of the primary use cases for IUOs.

I believe the recommended practice in cases like this is to declare peripheralManager like this:


private var peripheralManager: CBPeripheralManager! = nil


That allows you to set it explicitly after the super.init (). The rationale is that peripheralManager is genuinely, unavoidably nil for part of its lifetime (until it can be safely set), and so it must be some kind of optional. Using "!" rather than "?" allows this to happen without forcing users of the property to know about it.

private var peripheralManager: CBPeripheralManager! = nil

Aka an implicitly unwrapped optional.

How to insure lazy var instantiated in init()?
 
 
Q