Charlie Charlie - 5 months ago 7
Swift Question

How to assign an array of int and strings into one string variable in swift?

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:

  • You could use let (name, _) = totalDoubleSet1Array[i] syntax, or
  • You could use 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 }