dimanche 19 juin 2016

Random number with user defined range

I am teaching myself Swift and am stuck with a Random function.

What I want to achieve: User is able to specify the min and max of the Range.

Code I have now for the button, where I believe I am declaring the text as an integer:

@IBAction func generateNumbers(sender: AnyObject) {

    let minRange:Int? = Int(lowValue.text!)
    let maxRange:Int? = Int(highValue.text!)

    func randomNumber(range: Range<Int> = minRange...maxRange) -> Int {
        let min = range.startIndex
        let max = range.endIndex
        return Int(arc4random_uniform(UInt32(max - min))) + min
    }
}

Obviously minRange and maxRange aren't valid integers for the Range, I am just wondering where I'm going wrong.

Thanks in advance for any assistance.

Edit: I have tested that min/maxRange are valid Ints with:

    let results = minRange! + maxRange!

    self.field1.text = String(results)




Aucun commentaire:

Enregistrer un commentaire