Search code examples
swiftinstance-variables

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.


Solution

  • 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()
    }