MakeSchool-Tutorials / Getting-Started-With-Swift-2017

0 stars 2 forks source link

Card Challenge: Random Index #13

Closed TheoBendixson closed 7 years ago

TheoBendixson commented 7 years ago

I was going through this exercise, and it occurred to me that we might want to tidy up the random number generator code by giving students a function they can call.

My drawOne() function had all this ugly casting going on: func drawOne() -> Card? { guard cards.count > 0 else { return nil } let index = Int(arc4random_uniform(UInt32(cards.count))) return cards.remove(at: index) }

Proposed Solution: Give students a random integer function to take this burden off of their shoulders.

func randomInteger(maxiumum: Int) -> Int { return Int(arc4random_uniform(UInt32(maxiumum))) }

If we do this, we can reduce the amount of time spent fighting with the compiler while increasing the amount of time spent engaging with the more interesting problem: modeling a deck of cards. We could also do away with the need to explain arc4random_uniform and all the casting to and from different types of Int.

We can just say "Here's a random index function. It works like this. Call it."