Print 2 joined arrays in alphabetical order and in descending order

Right now my code prints its string array in alphabetical order. What I would like to do is is organize the array in a way like [a,1],[a,2],[b,4). Alphabetical order then in the int descending order. Right now you can see in my photo bellow what the code bellow is doing.

  var yourArray = [String]()
var number = [Int]()

class ViewController: UIViewController {

    @IBOutlet var labez: UILabel!
    @IBOutlet var textA: UITextField!
    @IBOutlet var textB: UITextField!

    @IBAction func store(_ sender: Any) {
        yourArray.append((textA.text!))
        number.append(Int(textB.text!)!)



        let d = yourArray.enumerated().map { (index,string) -> String in
            guard  number.count > index else { return "" }
            return "\(string )\(" ")\(number[index]) "
        }


        let sortedArray:[String] = d.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }


        labez.text = sortedArray.map { " \($0)" }.joined(separator:"\n")

    }

For your reference

import UIKit

struct Item: Comparable {
  var string: String
  var number: Int
  
  static func ==(lhs: Item, rhs: Item) -> Bool {
    return (lhs.string == rhs.string) && (lhs.number == rhs.number)
  }
  
  static func <(lhs: Item, rhs: Item) -> Bool {
    if lhs.string == rhs.string {
      return lhs.number > rhs.number
    } else {
      return lhs.string < rhs.string
    }
  }
}

class ViewController: UIViewController {
  @IBOutlet weak var stringTextField: UITextField!
  @IBOutlet weak var numberTextField: UITextField!
  @IBOutlet weak var outputLabel: UILabel!
  
  var itemArray = [Item]()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    outputLabel.numberOfLines = 0
  }

  @IBAction func buttonTapped(_ sender: UIButton) {
    guard let string = stringTextField.text,
      !string.isEmpty,
      let numberString = numberTextField.text,
      let number = Int(numberString) else {
        outputLabel.text = "Invalid input"
        return
    }
    
    let newitem = Item(string: string, number: number)
    itemArray.append(newitem)
    
    let sortedArray = itemArray.sorted()
    
    let output = sortedArray.reduce("") { (result: String, item: Item) -> String in
      return "\(result)\n\(item.string) \(item.number)"
    }

    outputLabel.text = output
  }
}

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