【问题标题】:How can I change the order of two arrays when one array is sorted? [duplicate]对一个数组进行排序时,如何更改两个数组的顺序? [复制]
【发布时间】:2018-04-21 16:59:12
【问题描述】:

如果我有:

var arrayOne = ["dog", "cat", "hamster", "horse"]​

var arrayTwo = [3, 2, 4, 1]

如何将3 分配给dog2 分配给cat4 分配给hamster,以及1 分配给horse,这样如果我从最大整数中对arrayTwo 进行排序最小,它也会自动为arrayOne 执行此操作。结果它会打印出来:

var arrayOne = ["hamster", "dog", "cat", "horse"]

var arrayTwo = [4, 3, 2, 1]

什么代码最简单最简单?

提前致谢! :)

【问题讨论】:

  • 将它们保存在一个数组、一个元组或另一个对象(字典、自定义结构/对象等)中。不要保留 2 个数组,这正是使它们不同步的最佳方式。
  • 您最好定义一个具有两个属性的Animal 结构或类:idname。数组很快就会变得混乱
  • 这很有趣,当我回来的时候,问题已经解决了,但是任何人......这就是我想出的:gist.github.com/staticVoidMan/19175de6ea9021eaa27d3b5cf4d432ba

标签: ios swift xcode


【解决方案1】:

很难将这两个变量“绑定”在一起。你可以这样做:

let dict = [3: "dog", 2: "cat", 4: "hamster", 1: "horse"]

var arrayTwo = [3, 2, 4, 1] {
    willSet {
        // you should probably check whether arrayTwo still has the same elements here
        arrayOne = newValue.map { dict[$0]! }
    }
}

压缩数组然后按arrayTwo排序更容易:

let result = zip(arrayOne, arrayTwo).sorted(by: { $0.1 > $1.1 })

现在,result.map { $0.0 } 是您的排序数组 1,result.map { $0.1 } 是您的排序数组 2。

【讨论】:

  • 感谢您的所有回答!抱歉耽搁了:(他们都很有帮助。
猜你喜欢
  • 1970-01-01
  • 2011-06-06
  • 2016-09-01
  • 2018-06-14
  • 2015-06-08
  • 2013-11-10
  • 1970-01-01
  • 2016-07-14
  • 2013-12-24
相关资源
最近更新 更多