简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM