Search code examples
arraysswiftarc4random

Why do I get this error and how can I fix it? Swift


I am making a guess the card game and i get this weird error which I cannot fix when I create a random number for the symbols and the card numbers. This is the error:

An image of the error

let cardSymbols = ["Spades", "Hearts", "Diamonds", "Clubs"]
let numbers = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

func getRandomCard() {

    var correctSymbolNumber = arc4random_uniform(UInt32(cardSymbols.count - 1))
    var correctNumberNumber = arc4random_uniform(UInt32(numbers.count - 1))

    var correctSymbol = cardSymbols[correctSymbolNumber]
    var correctNumber = numbers[correctNumberNumber]

}

How can I fix this? I know the problem is with my arc4random... but how can I fix it.


Solution

  • You need to change the result of arc4random_uniform to a swift Int, currently it is a UInt32 which you cannot use for a swift dictionary or array.

    So:

    var correctSymbolNumber = Int(arc4random_uniform(UInt32(cardSymbols.count - 1)))
    var correctNumberNumber = Int(arc4random_uniform(UInt32(numbers.count - 1)))
    
    var correctSymbol = cardSymbols[correctSymbolNumber]
    var correctNumber = numbers[correctNumberNumber]