First of all, a few comments.
- There is no need for nested classes or even a custom class at all
- Just use an array of Strings
- add to array like this :
array.append(Item)
- Do not initialise as
AnyObject in a language that is aware of types. (let entry: AnyObject = city.cities[indexPath.row])
In your example you have a collection of Strings so I would just use this:
var cities : [String] = []
cities.append("NY")
let city = cities[0] // NY
You also stated that you have a part of your code in a different file. I am assuming you want to have a method for fetching and storing the values. And a separate method to display them?
I would propose making two classes if you want to handle more than just a City Name and want to have access to the fetched data anywhere in your app.
Google Singleton for more info on how this works.
class City {
var name : String = ""
var geoLocation : CLLocationCoordinate2D?
// more attributes of your city object
init(name name_I: String) {
self.name = name_I
}
}
class Locations {
// the static part is shared between all instances of the Locations Class -> Google Singleton
static var cachedLocations : Locations = Locations()
var cities : [City] = []
init() {
}
}
// add a new city
let newCity = City(name: "NY")
Locations.cachedLocations.cities.append(newCity)
// in another class / file / viewcontroller ,.... get the cached city
let cachedCity = Locations.cachedLocations.cities[0]
You could add a class function to Locations to convert between a Dictionary and the City class. How to get a Dictionary from JSON
// class function is available without needing to initialise an instance of the class.
class func addCachedCity(dictionary:[String:AnyObject]) {
guard let cityName = dictionary["name"] as? String else {
return
}
let newCity = City(name: cityName)
cachedLocations.cities.append(newCity)
}
This would be used like this:
let cityDict : [String:AnyObject] = ["name":"LA"]
Locations.addCachedCity(cityDict)
Locations.cachedLocations.cities // now holds NY and LA
let cities = []should give you a compiler error. Swift won't know if it's an empty array or empty dictionaryarray.append(Item)