gpt4 book ai didi

ios - Swift 数组与另一个数组引用获取值

转载 作者:搜寻专家 更新时间:2023-11-01 06:57:59 25 4
gpt4 key购买 nike

在我的场景中,我有两个具有相同计数的独立数组。我正在将 array_one 显示到我的选择器或表格中。我不显示 array_twoarray_one 我将在 table 或 picker View 中显示。当用户单击特定索引时,我可以获得 array_one 值,但同时我还需要获得相关 ID(array_two)。如何做到这一点,请提供一些示例。

   Var array_one = [“Hindi”,”English”,”Bengali”,”Telugu”,”Odia”]
Var array_two = [“05”,”02”,”08”,”02”,”09”]

上面,数组我有语言和ID。当我选择与语言相关的索引 ID 时,我在选择器或 TableView 中列出语言,我也需要获取。 输出如:“Hindi, 05”

最佳答案

试试这个:

let array_one = ["Hindi","English","Bengali","Telugu","Odia"]
let array_two = ["01","02","03","04","05"]

let language = "Hindi"

guard let index = array_one.index(of: language) else {
fatalError("Couldn't find the language")
}

let languageId = array_two[index]

let output = language + ", " + languageId


print(output) //"Hindi, 01"

实际上,不需要array_two:

let array_one = ["Hindi","English","Bengali","Telugu","Odia"]

let language = "Hindi"

guard let index = array_one.index(of: language) else {
fatalError("Couldn't find the language")
}

let languageId = String(format: "%02d", index + 1)

let output = language + ", " + languageId

这是一个使用 zip 的解决方案:

let array_one = ["Hindi","English","Bengali","Telugu","Odia"]
let array_two = ["01","02","03","04","05"]
let zipped = zip(array_one, array_two)

let language = "Hindi"

guard let index = array_one.index(of: language),
let languageAndId = zipped.first(where: {$0.0 == language
})
else {
fatalError("Couldn't find the language")
}

let output = languageAndId.0 + ", " + languageAndId.1

print(output) //prints "Hindi, 01"

要拥有面向对象的编程方法,请使用结构:

let array_one = ["Hindi","English","Bengali","Telugu","Odia"]
let array_two = ["01","02","03","04","05"]

struct Language {
let name: String
let index: String
}

let languagesArray: [Language] = zip(array_one, array_two).map{Language(name: $0.0, index: $0.1)}

let language = "Hindi"

guard let languageAndId = languagesArray.first(where: {$0.name == language
}) else {
fatalError("Couldn't find the language")
}

let output = languageAndId.name + ", " + languageAndId.index

//prints "Hindi, 01"

关于ios - Swift 数组与另一个数组引用获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52373619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com