I have an array that takes in 2 types, a String and an Int the code looks like so
var totalDoubleSet1Array = [(Dante,10), (Cassius, 9), (Rio, 5)]
let sortedArray = totalDoubleSet1Array.sort { $0.1 > $1.1 }
I then use the sort function to arrange in order the highest score(Int) to the lowest with the name next to it. (So I can assign this to a string and display in an AlertAction) I have seen it somewhere on here that yes I can print an Array of a single type of String or Int etc to the console but how can I Assign this array of 2 types (Stings and Ints) to a new Variable of String so I can assign it to a AlertAction message in swift please? Or even better how can I grab the individual element of each entry so I can assign it to a Var String? Hopefully this makes sense.. Thanks
This is not an "array of two types", it's an array of tuples . You can grab an item from the array and take its individual parts like this:
let (name, score) = totalDoubleSet1Array[i]
After this assignment you would get two variables - name
of type String
that has the value of i
-th element's name, and score
of type Int
that has the value of i
-th element's score.
If all you need is the name, you have two options:
let (name, _) = totalDoubleSet1Array[i]
syntax, or let name = totalDoubleSet1Array[i].1
instead. Note that you are using the second syntax already in the comparison expression of your sorting function:
sort { $0.1 > $1.1 }
According Apple tuples are not the best choice for data structures...
Why not just using a custom struct
struct Player {
var name : String
var score : Int
}
let totalDoubleSet1Array = [Player(name:"Dante", score:10), Player(name:"Cassius", score:9), Player(name:"Rio", score:5)]
let sortedArray = totalDoubleSet1Array.sort { $0.score > $1.score }
Then you can easily access the name for example in a table view
let player = sortedArray[indexPath.row]
nameLabel.text = player.name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.