Swift中的三个分层数组

时间:2019-03-30 06:54:50

标签: arrays swift multidimensional-array swift3

我只是学习Swift,如果这是一个简单的问题,请原谅。但是我真的很努力地拥有一个三层深的数组,并显示第三层数据。

我已经尝试过对此进行搜索,但是所有多维数组问题似乎都只针对2个级别。也许我需要以不同的方式来对待?

let cars = [
    ["volvo", ["red", "petrol", "automatic"], ["blue", "petrol", "manual"], ["white", "diesel", "automatic"]],
    ["bmw", ["green", "petrol", "manual"], ["white", "petrol", "manual"], ["white", "diesel", "automatic"]],
    ["ford", ["black", "diesel", "automatic"], ["grey", "diesel", "manual"], ["blue", "petrol", "automatic"]]
]
let catData = cars[0][3]

返回正常...但是,如果我尝试这样做:

let cars = [
    ["volvo", ["red", "petrol", "automatic"], ["blue", "petrol", "manual"], ["white", "diesel", "automatic"]],
    ["bmw", ["green", "petrol", "manual"], ["white", "petrol", "manual"], ["white", "diesel", "automatic"]],
    ["ford", ["black", "diesel", "automatic"], ["grey", "diesel", "manual"], ["blue", "petrol", "automatic"]]
]
let catData = cars[0][3][1]

我收到此错误:类型为“ Any”的值没有下标

我要做的就是通过使用三级阵列获取汽车的颜色或变速箱,但是我不确定这是否真的有用...帮助!

1 个答案:

答案 0 :(得分:2)

问题是您的阵列不是3D阵列:

["volvo", ["red", "petrol", "automatic"], ["blue", "petrol", "manual"], ["white", "diesel", "automatic"]]

 ^ this is a simple String                         ^ this is an array

因此,您的第二维是由String[String]组成的。

一个真实的3D数组将是[[[String]]],但是,由于您的第二层是由不同类型组成的,因此它变成了Any,整个类型变成了[[Any]]

解决方案,声明一个struct

struct CarModel {
   let color: String
   let fuel: String // could be replaced by an enum
   let gear: String // could be replaced by an enum
}

let cars: [String: [CarModel]] = [
    "volvo": [
       CarModel(color: "red", fuel: "petrol", gear: "automatic"),
       CarModel(color: "blue", fuel: "petrol", gear: "manual"),
       CarModel(color: "white", fuel: "diesel", gear: "automatic")
     ]
]

print(cars["volvo"]![2].fuel)