1

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

2 Answers 2

3

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this will try it and get back to you.. Im a rookie at this language and am learning and so thanks for the insight =) Awesome it works!
2

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

1 Comment

Thanks for the insight, I am learning this lang so will look into it. Appreciate the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.