Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...


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?



Consider the following code: var defaults = NSUserDefaults.standardUserDefaults() var userPref..

Answer / 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

More Apple iOS Swift Interview Questions

What is mvvm in swift?

0 Answers  


How would you define variables and constants in swift programming language?

0 Answers  


Is swift an oop?

0 Answers  


What are the new feature in swift 4.0?

0 Answers  


Is swift easier than python?

0 Answers  


Is swift thread safe?

0 Answers  


Why do we use swift? Mention some advantages of swift?

0 Answers  


What are lazy stored properties, and how are they useful?

0 Answers  


How do I add a header in swift?

0 Answers  


How should errors be handled in swift?

0 Answers  


What are the collection types that are available in swift?

0 Answers  


What is encapsulation in swift?

0 Answers  


Categories