Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Simple iPhone App with Swift Structs As Data Models Finishing Up Our Model

Johnny Nguyen
Johnny Nguyen
3,875 Points

Can I do random like this? How Pasan's way different from me?

func random(_ n:Int) -> Int { return Int(arc4random_uniform(UInt32(n))) }

@IBAction func changeLabel() {

    funFactLabel.text = factProvider.facts[random(factProvider.facts.count)]

    }


}

3 Answers

Yes this can be done. Pasan is using the standard methods but using custom in a case like this is 100% fine.

You can use the arc4random_uniform as an alternative way to generate a random number; however, in addition to using a different method for generating a random number, Pasan is actually trying to get you to generate a random fact (String) as the return value, not just the index (he actually passes this value through as a part of the method itself). So, in order to achieve the same thing as the video — but while using your method instead of the GameKit random generator option — you'd want to:

struct FactProvider {

    let facts = [  "My first fact goes here",
                         "This is the second fact",
                         "A third fact can be placed here on this line",
                         "Fourth fact of the array goes here",
                         "I love facts"  ]

    // Arc4Random_uniform number generator
    func random(_ n:Int) -> String {
        return facts[Int(arc4random_uniform(UInt32(n)))]
    }

}

And in the view controller file, you'd instead add:

funFactLabel.text = factProvider.random(factProvider.facts.count)

The main reason for why you'd want to do this (generate an actual fact rather than simply an index value that you have to pass through) is that you can actually pass the final value around more easily, and this better achieves the DRY (Don't Repeat Yourself) principle by cutting down on the code required. :thumbsup:

Hope this explains the difference a little better!!

I believe in the current version of Swift you can also do

Int.random(in: range)