简体   繁体   中英

Swift 2D array with different types

Is it possible to have a multi-dimentional array that has more than one data type.

Example (I want the last item to be an Int):

var london = [[String]]()

london[0] = ["England", "Chelmsford", 49]
london[1] = ["Wales", "Cardiff", 212]
london[2] = ["Scotland", "Glasgow", 556]
london[3] = ["Germany", "Frankfurt", 640]

I think you are better off with an array of struct or Dictionary :

struct CityInfo {
    var country : String
    var city : String
    var data : Int
}

var london = [CityInfo]()
london.append(CityInfo(country: "England", city: "Chelmsford", data: 49))
london.append(CityInfo(country: "Wales", city: "Cardiff", data: 212))
london.append(CityInfo(country: "Scotland", city: "Glasgow", data: 556))
london.append(CityInfo(country: "Germany", city: "Frankfurt", data: 640))

But you can use 2D array if you want:

var london = [[Any]]()    
london.append(["England", "Chelmsford", 49])
london.append(["Wales", "Cardiff", 212])
london.append(["Scotland", "Glasgow", 556])
london.append(["Germany", "Frankfurt", 640])

You use an array with in that array one of 2 options

either make it a class or struct containing the country/city/integer as properties

or

use a tuple typealias myData = (country: String, city: String, myNumber:Integer)

what use depends on what you'll do with it in your code

If you really want it like how you have it, just use AnyObject as the type

var london = [[AnyObject]]()

    london.append(["England", "Chelmsford", 49])
    london.append(["Wales", "Cardiff", 212])
    london.append(["Scotland", "Glasgow", 556])
    london.append(["Germany", "Frankfurt", 640])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM