[swift-users] Re-initializing lazy vars

Joanna Carter joanna at carterconsulting.org.uk
Sat Oct 21 04:27:46 CDT 2017


> It just seems so obvious to create-if-nil, and makes it nice to reset stuff that should be re-created. In my case, after my NSURLSession gets invalidated, I wanted to set the property to nil, and next time a session was needed, it would just get created.

The only thing I would query with the whole concept of resetting an implicitly unwrapped optional var is, with a simple example struct :

public struct TestStruct
{
  private var _description: String?
  
  public var description: String!
  {
    get
    {
      return _description ?? ""
    }
    set
    {
      _description = newValue
    }
  }
}

… test code would be :

  {
    var test = TestStruct()
    
    test.description = nil
    
    let str: String = test.description
  }

The idea of setting a var to nil and then getting a valid object back seems a bit anachronistic.

I think I would rather add an explicit "reset" method.

Joanna

--
Joanna Carter
Carter Consulting



More information about the swift-users mailing list