Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 根据另一个数组对数组进行排序,swift_Arrays_Swift_Function_Sorting - Fatal编程技术网

Arrays 根据另一个数组对数组进行排序,swift

Arrays 根据另一个数组对数组进行排序,swift,arrays,swift,function,sorting,Arrays,Swift,Function,Sorting,我想知道是否有任何内置函数可以根据另一个数组对数组进行排序。例如:根据TestInArray对testStringArray排序 var testStringArray=[“a”、“b”、“c”、“d”、“e”] var testIntArray=[21,3,43,5,1] 函数之后,testStringArray将 testIntArray.sort // [1, 3, 5, 21, 43] testStringArray // ["e", "b", "d", "a", "c"] var a

我想知道是否有任何内置函数可以根据另一个数组对数组进行排序。例如:根据TestInArray对testStringArray排序

var testStringArray=[“a”、“b”、“c”、“d”、“e”]
var testIntArray=[21,3,43,5,1]

函数之后,testStringArray将

testIntArray.sort // [1, 3, 5, 21, 43]
testStringArray // ["e", "b", "d", "a", "c"]
var array1=[“a”、“b”、“c”、“d”、“e”]
var array2=[21,3,43,5,1]
让sorted=zip(array1,array2)。排序{$0.1<$1.1}
array1=sorted.map{$0.0}
array2=sorted.map{$0.1}
打印(阵列1)/[“e”、“b”、“d”、“a”、“c”]
打印(阵列2)/[1,3,5,21,43]
像这样的?我觉得可以做得更好

zip(array1, array2).sort { $0.1 < $1.1 }.forEach {
    array1.removeAtIndex(array1.indexOf($0.0)!)
    array1.insert($0.0, atIndex: array1.count)

    array2.removeAtIndex(array2.indexOf($0.1)!)
    array2.insert($0.1, atIndex: array2.count)
}

print(array1) // ["e", "b", "d", "a", "c"]
print(array2) // [1, 3, 5, 21, 43]
编辑:

这感觉不太好

zip(array1, array2).sort { $0.1 < $1.1 }.forEach {
    array1.removeAtIndex(array1.indexOf($0.0)!)
    array1.insert($0.0, atIndex: array1.count)

    array2.removeAtIndex(array2.indexOf($0.1)!)
    array2.insert($0.1, atIndex: array2.count)
}

print(array1) // ["e", "b", "d", "a", "c"]
print(array2) // [1, 3, 5, 21, 43]
zip(array1,array2).sort{$0.1<$1.1}.forEach{
array1.removeAtIndex(array1.indexOf($0.0)!)
array1.insert($0.0,atIndex:array1.count)
array2.removeAtIndex(array2.indexOf($0.1)!)
array2.insert($0.1,atIndex:array2.count)
}
打印(阵列1)/[“e”、“b”、“d”、“a”、“c”]
打印(阵列2)/[1,3,5,21,43]

是的。我正试图找到排序的最简单方法,因为我的方法是定义一个新函数,根据第一个数组对第二个数组进行排序。只是我觉得我可以多走一步:)耶。你的比我的简单得多。谢谢你的帮助我认为你的第一种方法更好,因为我不想修改数组。