ios - calling function in viewDidLoad crash -


calling parsestring crashes application. myoptionalstring getting set didselectrowatindexpath in tableview. information passed view controller.

the method works if called button press. in life cycle method try unexpectedly found nil while unwrapping optional.

override func viewdidload() {     super.viewdidload()        if let myunwrappedstring = myoptionalstring{          print(myunwrappedstring) //<-- prints out string          confidence.text = parsestring(myunwrappedstring) //<-- unexpectedly found nil while unwrapping optional crash     }         }  //this method works if called on button press crashes in viewdidload func parsestring(mystring: string)->string{     return mystring.substringfromindex(mystring.rangeofstring(" ")!.endindex) } 

your error come function parsestring, let's see why. if see function you're make force-unwrapping of optional value in case mystring.rangeofstring(" ")!. not recommended @ all.

if pass string "confidence: 63%" function function works , returns "63%", works because have " " string inside, if reason pass string don't have it crash (e.g "confidence:63%").

so 1 of correct ways of implement function can using guard statement using optional binding avoiding force-unwrapping:

func parsestring(mystring: string) -> string? {    guard let range = mystring.rangeofstring(" ") else { return nil }    return mystring.substringfromindex(range.endindex) } 

in above function return nil in case of not exist " " in string , avoid runtime error.

i hope you.


Comments