我有一个多维数组,我试图使用一个变量(在下面的代码段中为 "ageVariable")来引用其中一个成员名,就像使用变量 "ageRangeSelected "来引用元素一样。
这是我的代码。
let time = Journey[ageRangeSelected].ageVariable
ageVariable可以是 "白天","晚上 "或者 "夜晚"。
这可能吗?按照我的写法,我得到以下错误。
"'旅程'类型的值没有成员'ageVariable'"
下面是定义数组的代码--我希望能够使用一个变量访问成员 "白天"、"晚上 "或 "夜晚"。
struct Journey: Identifiable, Equatable {
let id: Int
let age: String
let day: Int
let evening: Int
let night: Int
let drivers: Int
}
func createJourneyMale() -> (Array<Journey>) {
let journeyMale1720 = Journey(id: 1, age: "17-20", day: 4521, evening: 1243, night: 946, drivers: 440)
let journeyMale2129 = Journey(id: 2, age: "21-29", day: 5302, evening: 1254, night: 737, drivers: 1877)
let journeyMale3039 = Journey(id: 3, age: "30-39", day: 5874, evening: 1166, night: 572, drivers: 3015)
let journeyMale4049 = Journey(id: 4, age: "40-49", day: 6358, evening: 1298, night: 616, drivers: 3282)
let journeyMale5059 = Journey(id: 5, age: "50-59", day: 6710, evening: 1155, night: 594, drivers: 2877)
let journeyMale6069 = Journey(id: 6, age: "60-69", day: 6534, evening: 814, night: 418, drivers: 2388)
let journeyMale70 = Journey(id: 7, age: "70+", day: 5643, evening: 495, night: 242, drivers: 2156)
let journeyMale = [journeyMale1720, journeyMale2129, journeyMale3039, journeyMale4049, journeyMale5059, journeyMale6069, journeyMale70]
return (journeyMale)
}
let Journey = createJourneyMale()
首先没有多维数组。这是一个简单的一维数组。
第二,在命名一个代表数组的变量时,总是用复数形式,并且命名变量时总是以小写字母开头。
let journeys = createJourneyMale()
第三,所有变量的参数 return
和返回值不是函数,所以括号会引起误导和混淆。
func createJourneyMale() -> Array<Journey> {
...
return journeyMale
使用一个变量来访问多个不同的属性的唯一方法是用一个 keyPath
let ageVariable = \Journey.evening
let time = journeys[ageRangeSelected][keyPath: ageVariable]