Search code examples
swiftclassvariablesinitialization

Initialize a class in Swift


Maybe this is super basic stuff, but I'm still not sure the difference between the following codes in Swift.

  • private let myViewController = MyViewController()
  • private let myViewController: MyViewController!

I used them interchangeably when I make a variable in Swift, but is there a difference between them? Also, is there a specific name for the way it is initialized? (I want to do some Google search for the difference between the code above, but since I'm not sure the name of the initialization, I can't Google search now...).


Solution

  • private let myViewController = MyViewController() means myViewController have instance of MyViewController class whenever it will be used in class.

    But private let myViewController: MyViewController! in that case we must assign the instance of MyViewController to myViewController before using myViewController otherwise there will be a crash.