1

Here is my simple swift class:

class SessionInitTest: NSObject, NSURLSessionDataDelegate {
    let session: NSURLSession!

    override init() {
        super.init()
        session = NSURLSession(configuration: nil, delegate: self, delegateQueue: nil)
    }
}

the Xcode complaints that in the line of super.init():"Property 'self.session' not initialized at super.init call". And the init of session:"Immutable value 'self.session' may only be initialized once". According to need self to set all constants of a swift class in init, why session is not set to nil before super.init()?

Community
  • 1
  • 1
D.Young
  • 113
  • 1
  • 7
  • Only a *variable* IUO is initialized to `nil`. Compare http://stackoverflow.com/questions/30517167/implicitly-unwrapped-optionals-in-swift-does-not-seem-to-work, http://stackoverflow.com/questions/29956702/unable-to-declare-swift-implicitly-unwrapped-optional-as-a-constant for similar problems. – Martin R Jun 01 '15 at 11:47
  • So the only solution is to change 'let' to 'var', which substitute the constant by a variable to give a default nil value before 'super.init()'? We can't have a constant 'session' after initialisation? – D.Young Jun 01 '15 at 12:08
  • 1
    `let session` can only be initialized once, and it can only be `nil` before `super.init()` is called because `self` isn't "valid" then. *I* do not know how to do it with a *constant*, perhaps someone else does. Another similar problem here: http://stackoverflow.com/questions/29551619/swift-1-2-self-used-before-super-init-call. – It may be that older Swift versions allowed to re-assign a constant within init methods, but that is not possible in Swift 1.2 – Martin R Jun 01 '15 at 12:23
  • Thank you! I thought a default `nil` before `super.init()` will be given to `session` according to "Unowned References and Implicitly Unwrapped Optional Properties." chapter in "Swift Programming Language". It seems this has changed since Swift 1.2 – D.Young Jun 01 '15 at 12:40

0 Answers0