Consider the following code:

var defaults = NSUserDefaults.standardUserDefaults()

var userPref = defaults.stringForKey("userPref")!

printString(userPref)

func printString(string: String) {

println(string)

}

Where is the bug? What does this bug cause? What’s the proper way to fix it?

Answer Posted / iosraj

The second line uses the stringForKey method of NSUserDefaults, which returns an optional, to account for the key not being found, or for the corresponding value not being convertible to a string.

During its execution, if the key is found and the corresponding value is a string, the above code works correctly. But if the key doesn’t exist, or the corresponding value is not a string, the app crashes with the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

The reason is that the forced unwrapping operator ! is attempting to force unwrap a value from a nil optional. The forced unwrapping operator should be used only when an optional is known to contain a non-nil value.

The solution consists of making sure that the optional is not nil before force-unwrapping it:

let userPref = defaults.stringForKey("userPref")

if userPref != nil {

printString(userPref!)

}

An even better way is by using optional binding:

if let userPref = defaults.stringForKey("userPref") {

printString(userPref)

}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is retain in swift?

459


What are the new feature in swift 4.0?

478


What is init() in swift?

483


Is apple using swift?

449


What is closure in swift?

482






What are regular expression and responder chain in swift?

615


What is encapsulation in swift?

491


What is swift stand for?

455


Explain mvc structure.

481


Explain the difference between let and var in swift programming?

475


Is swift pass by reference?

436


What is differences in swift 1.x, 2.x, 3.x, 4.x?

470


What is bridging header in swift?

438


Is swift object oriented programming?

536


Explain what is half-open range operator?

460