I am following along a tutorial and I am confused with why there are () at the end of the array which will hold instances of Car.
class CarModel {
var cars = [Car]()
init () {
...
}
}
Can someone explain how this is working.
CodePudding user response:
Most initialisers can be used without typing the .init
name. So let someObject = SomeType()
would be the same as let someObject = SomeType.init()
.
Array
has an empty initialiser that will create an empty array.
// let emptyCarArray = Array<Car>.init()
let emptyCarArray = Array<Car>()
However, Swift also has a syntax shortcut for Array<Element>
which is [Element]
. So the above code is exactly the same as doing...
// let emptyCarArray = [Car].init()
let emptyCarArray = [Car]()
This can also be done by explicitly setting the type too...
let emptyCarArray: Array<Car> = []
let emptyCarArray: [Car] = []
All four lines of code in this do the same thing.