I have created a cities class, which consists of several City objects, each with specific data. Since the data is fixed, I want to assign it in the init() function of the Cities object.
// CASE 1 - ERROR
class Cities : NSObject {
var cityList:[City]
override init() {
cityList = []
let city = City()
city.fill("LA" , "USA")
self.cityList.append(city)
city.fill("Amsterdam" ,"Netherlands")
self.cityList.append(city)
city.fill("Beijing" , "China")
self.cityList.append(city)
Result: Beijing Beijing Beijing
// CASE 2 - CORRECT
class Cities : NSObject {
var cityList:[City]
override init() {
cityList = []
var city:City
city = City(name: "LA" ,country: "USA")
self.cityList.append(city)
city = City(name: "Amsterdam", country: "Netherlands")
self.cityList.append(city)
city = City(name: "Beijing" , country: "China")
self.cityList.append(city)
Result: LA, Amsterdam, Beijing
When I run this first script, I get a nice Cities object and the array has 3 cities in it, all Beijing.
In the Correct case, the data is assigned by the init function of object City. Now everything works as expected.
In both cases I have created only one City object: city. Why is this difference in Swift behaviour? Using Apple Swift version 2.1