Maciej Gieparda Maciej Gieparda - 22 days ago 10
Swift Question

Setting a title of a button from shuffled array - Swift

That's my code

func shuffle() {
let footballClubsInPoland = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: self.footballClubsInPoland)
option1.setTitle((footballClubsInPoland[0] as AnyObject).name, for: .normal)
option2.setTitle((footballClubsInPoland[1] as AnyObject).name, for: .normal)
print(footballClubsInPoland[0])
print(footballClubsInPoland[1])
}


My problem is that I can see in a console the objects, that were shuffled, but titles of my buttons are not loading in a simulator. What should I do?

Answer Source

When doing (footballClubsInPoland[0] as AnyObject you are casting the elements to AnyObject, and when calling .name you aren't actually referring to the name property of footballClubs.

So you should rather do:

func shuffle() {
    let footballClubsInPoland = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: self.footballClubsInPoland) as! [footballClubs]
    option1.setTitle(footballClubsInPoland[0].name, for: .normal)
    option2.setTitle(footballClubsInPoland[1].name, for: .normal)
    print(footballClubsInPoland[0])
    print(footballClubsInPoland[1])