简体   繁体   English

具有不同类型的Swift 2D阵列

[英]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): 示例(我希望最后一个项目是一个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 : 我认为您最好使用structDictionary数组:

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: 但是您可以根据需要使用2D数组:

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 您在该数组中使用2个选项之一的数组

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) 使用元组typealias myData =(国家/地区:字符串,城市:String,myNumber:整数)

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 如果您真的想要它,就像使用它一样,只需使用AnyObject作为类型

var london = [[AnyObject]]()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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