Brian Brian - 4 months ago 29
iOS Question

calling function in viewDidLoad crash

Calling parseString crashes my application. myOptionalString is getting set from didSelectRowAtIndexPath in a tableview. The information is definately get passed to this viewcontroller. The method also works if called from a button press. But in any life cycle method I try I get unexpectedly found nil while unwrapping an Optional.

override func viewDidLoad() {
super.viewDidLoad()
if let myUnwrappedString = myOptionalString{
print(myUnwrappedString) //<-- prints out string
confidence.text = parseString(myUnwrappedString) //<-- unexpectedly found nil while unwrapping an Optional crash
}
}

//this method works if called on a button press but crashes in viewDidLoad
func parseString(myString: String)->String{
return myString.substringFromIndex(myString.rangeOfString(" ")!.endIndex)
}

Answer

Your error come from your function parseString, let's see why. If you see carefully your function you're make a force-unwrapping of an optional value in your case the myString.rangeOfString(" ")!. This is not recommended at all.

If we pass the string "Confidence: 63%" to the function the function works properly and returns "63%", but it works because it have the " " string inside, if for some reason you pass some string that don't have it it will crash (e.g "Confidence:63%").

So one of the correct ways of implement this function can be using the guard statement using optional binding avoiding any force-unwrapping:

func parseString(myString: String) -> String? {
   guard let range = myString.rangeOfString(" ") else { return nil }
   return myString.substringFromIndex(range.endIndex)
}

In the above function you return nil in case of not exist the " " in the string and avoid the runtime error.

I hope this help you.