gpt4 book ai didi

arrays - 按 Int 数组对字符串数组进行排序

转载 作者:行者123 更新时间:2023-11-28 09:35:23 24 4
gpt4 key购买 nike

我想在另一个的帮助下订购一个数组,如下所示:

var names = [anna, berta, caesar, dora]
var sorting = [2, 0, 1, 3]

排序如下:

var sortedNames = [caesar, anna, berta, dora]

以便整数数组(“排序”)在其自己的值之后对字符串数组(“名称”)进行排序。我该怎么做?

我用for循环试过了,没用。

for i in 0...names.count
{
let x = "\(names[sorting]])"

sortedNames.append(x)
}
return history

最佳答案

您可以使用 map() 函数来转换 sorting 的值:

var names = ["anna", "berta", "caesar", "dora"]
var sorting = [2, 0, 1, 3]

let sortedNames = sorting.map({ names[$0] }) // ["caesar", "anna", "berta", "dora"]

Keep in mind that this solution only works if the values in sorting are valid indices for the names array.

关于arrays - 按 Int 数组对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557656/

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