richbrz
richbrz

Reputation: 92

Fatal error in Xcode - I know the cause but don't know how to fix it

code highlighted in green by Xcode (Thread 1: EXC_BAD_INSRTUCTION)

amountDueLabel.text = String(HomeViewController().getAllowanceDue())

the function getAllowanceDue()

func getAllowanceDue() -> Int{
    var allowance = allowanceTextField.text.toInt()
    return allowance!
}

thank you so much!

Go easy on me - I am a beginner in iOS development

Upvotes: 1

Views: 278

Answers (1)

tek3
tek3

Reputation: 2115

In Swift unlike Objective C, you have to explicitly let the compiler know that a variable can be 'nil' in future by marking that variable as optional (?).

toInt() method also returns an 'optional Integer value' which means toInt() method can also return 'nil' value in case it is not able to convert the supplied string value to integer value.

Here you are unwrapping the optional Int value with allowance! . But before unwrapping the optional value you must check if the optional value is not 'nil'.

func getAllowanceDue() -> Int {
    if let allowance = anotherString.toInt() {
        return allowance
    }
    return -1
}

By checking if let allowance = anotherString.toInt() we are actually using concept of Optional Binding in Swift to check whether optional contains a value.

Upvotes: 1

Related Questions