安排混乱的数组

时间:2015-09-19 18:22:08

标签: ios arrays swift swift2

在我的应用程序中,有一个名为SELECT ROW_NUMBER() OVER (PARTITION BY section_id ORDER BY 1), session_id FROM my_table ORDER BY 2 的数组,其中包含大量数字。应用程序将数字发送到服务器并将它们放入名为newArray的新数组中。我的问题是某些名称的返回速度比其他名称快,stalkers数组中的名称可以按任何顺序排列。如何使返回数据的顺序与stalkers中的相应数字相同?

所以,让我们说newArray。我的代码将它发送到服务器并下载名称。对于" 10002938948",服务器返回" Tim"。对于" 46789890"服务器返回" Louis"。对于" 2984829389",服务器返回" Rob"。然后它应该是newArray = ["10002938948","46789890","2984829389"],但因为它们没有按顺序下载(一个页面加载速度快于另一个页面),stalkers = ["Tim","Louis","Rob"]

这应该是我可以给每个号码一个id,所以我可以在stalkers = ["Louis","Rob","Tim"]数组中按正确的顺序对id进行排序。

1 个答案:

答案 0 :(得分:2)

使用newArray的元素作为键创建字典,并将到达的名称值作为值。当所有结果都到达后,通过循环stalkers创建newArray数组,从而保持顺序。

let newArray=["10002938948","46789890","2984829389"]

// For 10002938948, the server returns Tim. 
// For 46789890 the server returns Louis.
// For 2984829389, the server returns Rob.
// Then it should be stalkers=["Tim","Louis","Rob"]

// As they arrive, store each result in a dictionary:

var d = [String:String]()

// note that the order of the next three statements doesn't matter!

// Tim arrives for 10002938948

d["10002938948"] = "Tim"

// Louis arrives for 46789890

d["46789890"] = "Louis"

// Rob arrives 2984829389

d["2984829389"] = "Rob"

// now assemble stalkers by cycling through newArray

let stalkers = newArray.map{d[$0]!} // ["Tim","Louis","Rob"]