Eric Conner
Eric Conner

Reputation: 10772

Swift - difference between class level instantiation and method level instantiation

What is the difference between the following usages? Is there a difference?

class B { }

// usage 1
class A {
    var b: B = B();
}

// usage 2
class A {
   var b: B!

   init() {
      self.b = B()
   }
}

Edit: Some of the answers point out that in usage 2 the value does not need to be an optional since it gets a value in the initializer.

Upvotes: 3

Views: 247

Answers (3)

Cœur
Cœur

Reputation: 38727

Instantiation is done in the declarative order of the assignation statements. But class level statements (stored properties) are done before method level statements:

// in this example, the order will be C, D, B, A
class MyClass {
    init() {
        b = B()
        a = A()
    }

    var a: A
    var b: B
    var c: C = C()
    var d: D = D()
}

Upvotes: 3

KPM
KPM

Reputation: 10608

Assuming the extra ! in usage 2 is not something you meant, no there is absolutely no difference between

// usage 1
class A {
    var b: B = B();
}

and

// usage 2
class A {
   var b: B

   init() {
      self.b = B()
   }
}

It's exactly the same.

Upvotes: 0

WhatsUpNSDoc
WhatsUpNSDoc

Reputation: 139

Yes, there's a huge difference between these two. In usage 2, b is an implicitly unwrapped optional. When you do:

let a = A()

then a.b will be set in both cases, but in usage 2, somebody can then do:

a.b = nil

and then you'll get an error if you try to use it.

Upvotes: -1

Related Questions