0

So I have this class in City.swift:

class City {
    class Entry {
        let name : String
        init(name : String) {
            self.name = name
        }
    }

    let cities = []
}

And in another file I want to add to an array like this:

var city = City()
city.cities = City(name: "Test")

And I want to be able to call it by indexPath.row number (because I am using it in cellForRowAtIndexPath) like this:

let entry: AnyObject = city.cities[indexPath.row]
println(entry.name as String)

How could I make this code work?

5
  • 2
    your structure makes no sense. Can you explain why you need it to be like this? Commented Nov 2, 2015 at 13:19
  • 1
    let cities = [] should give you a compiler error. Swift won't know if it's an empty array or empty dictionary Commented Nov 2, 2015 at 13:20
  • 1
    @ZoffDino compile errors are the least problematic here. Commented Nov 2, 2015 at 13:20
  • Well I have a json array and I want to load this array in a swift array so I can call them with indexPath.row. Commented Nov 2, 2015 at 13:23
  • @SinanSamet Why don't you add them to an array in a way that is actually in the Swift language : array.append(Item) Commented Nov 2, 2015 at 13:25

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

8 Comments

You are right somehow I was just thinking too complicated about it.. But when I try it your way it says "Cannot invoke 'append' with an argument list of type '[String : String ]'..
Oh wait actually the problem is that I am trying to make an associative array but the way you do it it won't let me. I actually want something like this item.append(["name": "John", "lastname" : "Doe"])
@SinanSamet That would not work with what you need. You need to be able to fetch them with the index of your UICollectionView. What you are describing now is a Dictionary and you can use Int as the Key, but then it basically becomes an unsorted Array.
What I am trying to achieve is to make the class for this question actually because he actually has what I want (converting json array to swift array) stackoverflow.com/questions/26766654/swift-addobject
@SinanSamet You are not describing it precisely. What you want is a way to convert a json array item to a custom class. The Swift Array has very little to do with it. Because either you want to convert Json to a Dictionary or you want to convert to a custom class. Adding instances of that class to an Array is trivial and unrelated to your issue.
|
0

You could simply make your array an global array. You only have to define your array out of the class. And then use the .append() function

let cities = []

    class City {
    class Entry {
        let name : String
        init(name : String) {
            self.name = name
        }
    }

}

3 Comments

Why should he don`t do that?
Global values are not by definition wrong, else it would not be part of the language. But we can achieve the same effect in much better ways. Use a Singleton, or declare the shared data in AppDel, or don't use shared data and just use Delegates. Globals add more to technical debt in the long run than they help you by saving you a couple of minutes now.
@Lenny1357: Data encapsulation is one of the most important concepts of object oriented programming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.