YellowPillow
YellowPillow

Reputation: 4270

Confused about error message (lldb)

Say for example 13 was entered into the text field which is referenced by: numberField

@IBAction func calculateButton(sender: AnyObject) {

            var numInt = numberField.text.toInt()

            println(numInt) //outputs Optional(13)
            println(numInt!) //outputs 13

            if numInt != nil {

                var unwrappedNum = numInt!
                var isPrime = true
                println(unwrappedNum) //Crashes here and outputs (lldb)

                for var i = 1; i<unwrappedNum; i++ {
                    if unwrappedNum % i == 0 {
                        isPrime = false

                    }
                }
            }
}

I've checked online and I think the problem is that it is evaluating to nil but I don't understand how it would evaluate to nil when just outside the if statement it isn't nil.

Upvotes: 0

Views: 45

Answers (2)

LastMove
LastMove

Reputation: 2482

Oh I saw your problem is:

var numInt = numberField.text.toInt()

When "numberField.Text" is an empty String, it crashes.

Upvotes: 0

rakeshbs
rakeshbs

Reputation: 24572

Instead of the nil check, the swift way to do it is to use optional binding.

if let unwrappedNum = numInt
{
    println(unwrappedNum)
}

or simply you can do

if let numInt = numberField.text.toInt()
{
    println(numInt)
}

numInt will be unwrapped.

For more info read : http://www.appcoda.com/beginners-guide-optionals-swift/

Upvotes: 1

Related Questions