从另一个类

时间:2015-11-02 13:05:37

标签: ios swift

所以我在City.swift中有这个课程:

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

    let cities = []
}

在另一个文件中,我想添加到这样的数组中:

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

我希望能够通过indexPath.row编号调用它(因为我在cellForRowAtIndexPath中使用它),如下所示:

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

我怎样才能使这段代码有效?

2 个答案:

答案 0 :(得分:1)

首先,一些评论。

  • 不需要嵌套类,甚至不需要自定义类
  • 只使用一个字符串数组
  • 像这样添加到数组:array.append(Item)
  • 请勿使用了解类型的语言初始化为AnyObject。 (let entry: AnyObject = city.cities[indexPath.row]

在你的例子中,你有一个字符串集合,所以我只想使用它:

var cities : [String] = []
cities.append("NY")
let city = cities[0] // NY

您还声明您将部分代码放在不同的文件中。我假设你想要一个获取和存储值的方法。还有一个单独的方法来显示它们?

如果您想要处理的不仅仅是城市名称并且想要在您的应用中的任何位置访问所获取的数据,我建议制作两个类。 Google Singleton了解有关其工作原理的详细信息。

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]

您可以向Locations添加一个类函数,以便在DictionaryCity类之间进行转换。 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)
}

这将使用如下:

let cityDict : [String:AnyObject] = ["name":"LA"]
Locations.addCachedCity(cityDict)

Locations.cachedLocations.cities // now holds NY and LA

答案 1 :(得分:0)

您可以简单地将数组设为全局数组。你只需要定义 你的阵列出类。然后使用.append()函数

let cities = []

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

}
相关问题