Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Simple iPhone App with Swift Creating a Data Model Finishing Up Our Model

LUIS A HERNANDEZ PIÑA M
LUIS A HERNANDEZ PIÑA M
2,223 Points

In the random facts generator I did what was shown in the video, but I get: fatal error: Array index out of range.

func randomFact() -> String {
        var unsignedArrayCount = UInt32(factsArray.count)
        var usignedRandomNumber = arc4random_uniform(unsignedArrayCount)
        var randomNumber = Int(unsignedArrayCount)

        return factsArray[randomNumber]

// I did the same as in the video however I get fatal error: index out of range. How can the index be out of range if it is set to factsArray.count?

1 Answer

Andrew Shook
Andrew Shook
31,709 Points

you are not type casting the correct variable. See below:

func randomFact() -> String {
        var unsignedArrayCount = UInt32(factsArray.count)
        var usignedRandomNumber = arc4random_uniform(unsignedArrayCount)
        // your original code 
        // var randomNumber = Int(unsignedArrayCount)

        //what the code needs to be
        var randomNumber = Int(usignedRandomNumber)

        return factsArray[randomNumber]