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

How do you generate a random number now? Since the arc4random_uniform does not exist in swift 2.

In building a simple app that generates random facts, I can't figure out anywhere how to generate random numbers.

3 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Aaron Zheng,

So I believe that Pasan explains this in the Swift 2.0 track. It wouldn't be a bad idea for you to do the course Build A Simple iPhone App with Swift 2.0. It's the same app you're working on now. Let me see if I can help you solve the problem though.

In Swift 2.0, theres a better way to generate a random number. Using the GameKit framework.

// The first thing you need to do is import the GameKit framework
import GameKit

//Now we can use the GameKit framework to generate our random number using GKRandomSource

let randomNumber = GKRandomNumber.sharedRandom().nextIntWithUpperBound(upperBound: Int)

// For the upper bound argument, set it to the the name of your fact array and access .count on it

We use the .count property to determine the upperBound because this allows our code to be more flexible. If we hardcoded this value, instead of using .count, we would have to remember to change this anytime we changed the number of items in the fact array

eberhapa
eberhapa
51,495 Points

Is it good to use the whole gamekit import just for a random number?

David Montalvo
David Montalvo
6,937 Points

In fact it exists, it is just not shown by Xcode, if you use something like this, it will work!!

let randomNumber = Int(arc4random_uniform(UInt32(5))

That will create a random number from 0 to 5, so you can change the 5 by the number of random data you want, just remember to use the UInt32

You missed the last ) at the end.

let randomNumber = Int(arc4random_uniform(UInt32(5)))

Right - but you can still get the count by counting the facts in the model like so (presuming you're not hanging out in the model at the moment):

//get your top end of the range
let maxNumber = UInt32(facts.count)
let randomNumber = Int(arc4random_uniform(maxNumber))