mduttondev mduttondev - 1 year ago 98
Swift Question

Sort one String array to match another

What would be the cleanest way to sort one array to match another array:


public class Account {

public var identifier: String

init(id identifier:String) {
self.identifier = identifier


let knownOrder = ["abc", "klm", "def", "hij"]

var givenOrder = [Account(id: "abc"), Account(id: "def"), Account(id: "hij"), Account(id: "klm")]

what would be the easiest way to make the output for givenOrder match knownOrder without altering knownOrder?

Added a little more to the example. Im trying to get the given list of Account objects with an identifier property to be in the same order as a stored list of strings which match the users preference to have their accounts

Answer Source

Do you need something like that?

let knownOrder = ["a1", "b2", "c3", "d4"]
var givenOrder = ["c3", "a1", "d4", "b2"]

givenOrder.sort { (lhs, rhs) -> Bool in
    (knownOrder.index(of: lhs) ?? 0) < (knownOrder.index(of: rhs) ?? 0)

?? 0 is there in case if givenOrder contains values not in knownOrder, those values would be unsorted at the beginning of a list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download