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")
}
You should create an array of tuples from the two input arrays rather than an array of Strings. You can do this using zip
, than using a custom sorting function can easily solve the sorting issue. If the characters are different, you sort based on them alphabetically, but if they are the same, you sort based on the Int value.
@IBAction func store(_ sender: Any) {
yourArray.append((textA.text!))
number.append(Int(textB.text!)!)
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
}
})
print(sorted)
labez.text = sortedArray.map { " \($0)" }.joined(separator:"\n")
}