Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 884
Eric Conner Avatar asked Nov 16 '25 20:11

Eric Conner


1 Answers

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()
}
like image 143
Cœur Avatar answered Nov 19 '25 09:11

Cœur