Struct not keeping sorted order (swift4)

My code has 2 textfields one for int and the other for string. The way the code is supposed to be sorted is by ascending alphabetical order for the string (a-z)then by descending order for the int (9-1).So i entered 2 entries in a,2 a,1 order but the way the list is being displayed is a,2 a,1 which is not the sorted order. How can I keep the sorted order?


   @IBAction func move(_ sender: Any) {
    let tuples = zip(yourArray,number)

    let sorted = tuples.sorted(by: { this, next in
        if this.0 < next.0 {
            return true
        } else if this.0 == next.0 {
            return this.1 < next.1
        } else {
            return false
        }}) { " \($0)" }.joined(separator:"\n")))
struct bad {
static var mm = [String]()}


   override func viewDidLoad() {

let defaults = UserDefaults.standard
defaults.set(benCarson.text, forKey: "SavedStringArray2")

benCarson.text = String(describing:
benCarson.numberOfLines = 5000


Picture of result

Your question says you want to first sort by the name in ASCENDING order, and then by the number in DESCENDING order…and that’s exactly what you showed, so I’m not sure what you are saying your issue is. You should write your method like this though, since you’re comparing strings and you should handle localization instead of just assuming ascii ordering.

let sorted = tuples.sorted {
    let result = $0.0.localizedCaseInsensitiveCompare($1.0)
    if result == .orderedSame {
        return $0.1 > $1.1
    } else {
        return result == .orderedAscending

If you really want it to be numerically ASCENDING then just change the > to a < in the sort.

This topic was automatically closed after 166 days. New replies are no longer allowed.