Search code examples
iosswiftuint32

Runtime error when taking user input for a range


I'm trying to create some code in Swift that will take a user input, from a UITextField object, create a range from that input from 1 to X(User inputted number), and then pick a random number out of that range.

I am calling my user inputted text like this

var rangeInput: UInt32 {
    get {
        return ((rangeInputTextField?.text ?? "") as? UInt32)! // ERROR OCCURS HERE
    }
}

and creating my list and calling the number this way.

let viewController =  ViewController()
var x = ViewController().rangeInput
let y = (UInt32?(x))
var number = arc4random_uniform(y!)

//MARK: Class for random number

struct RandomNumber {
    // numberRange to change the value for 1...X(user input)
    //creates the list to be picked from. (pickRandom)
   func numberRange(high:  UInt32) ->Range<UInt32>{

        if let high = UInt32?(0) {
            print("Invalid number")
        } else { 
            let high = UInt32(y!) + 1
        }

        let range = 1...high
        return range

    }

    let pickRandom = number
}

and back in my view controller, I am calling it inside the function of my button, like this.

 @IBAction func rollButton(sender: UIButton) {

     rolledNumber?.text = "\(RandomNumber().pickRandom)"

     if let resignFirstResponder: Bool = resignFirstResponder() {
         self.rangeInputTextField?.resignFirstResponder()     //Closes keyboard
     }
     resignFirstResponder()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

Here is what confuses me, my code compiles and runs, when I get to the simulator, everything seems fine, I press my text field, and my number pad pulls up, and I can enter my number, but when I press the Roll button I have set up, it crashes. it gives me an error saying "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0)" and "fatal error: unexpectedly found nil while unwrapping an Optional value" in the cmd line

on this line

return ((rangeInputTextField?.text ?? "") as? UInt32)!

Solution

  • I solved my issue, i actually ended up scrapping my entire code, and creating a new struct.

    this is what worked for me:

    struct RandomNumber {
    func getRandomNumber(x: UInt32) -> String{
        return String(arc4random_uniform(x) + 1)
    }
    

    }

    all I have to do is call on the struct from my view controller