0

I have simple code:

struct User {
    let id: Int
    let name: String
}

var users: [User] = [User(id:1, name:"Alpha"), User(id:2, name:"Beta"), User(id:3, name:"Gamma")]

print(users)
users.sort { $0.name > $1.name }
print(users)

What is the best way of changing the sorting field based on variable? I mean, I want to have some variable like "sortBy" which contains value of sorting field ("id", "name" etc, struct may contain dozens of fields). And I can't find out the proper way of doing so in Swift.

Pseudo-code:

var sortBy = "name"
users.sort { $0.{sortBy} > $1.{sortBy} }

1 Answer 1

1

Use key paths and methods.

users.sort(by: \.name)
users.sort(by: \.id)
extension Array where Element == User {
  mutating func sort<Comparable: Swift.Comparable>(
    by comparable: (Element) throws -> Comparable
  ) rethrows {
    self = try sorted(by: comparable, >)
  }
}
public extension Sequence {
  /// Sorted by a common `Comparable` value, and sorting closure.
  func sorted<Comparable: Swift.Comparable>(
    by comparable: (Element) throws -> Comparable,
    _ areInIncreasingOrder: (Comparable, Comparable) throws -> Bool
  ) rethrows -> [Element] {
    try sorted {
      try areInIncreasingOrder(comparable($0), comparable($1))
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.