func doGetLocalDataUser() -> logInResponse {
var localData : logInResponse? = nil
if let userData = UserDefaults.standard
.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA),let user = try? JSONDecoder()
.decode(logInResponse.self ,from: userData){
localData = user
}
return localData!
}

- 2,587
- 3
- 27
- 43
-
if logInResponse != nil then if UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA) != nil maybe...anyway, start learning to think before code. No rude, just a clear advice. Play with guard for safe. You tell in code localData is optional, then you return as ! – ares777 Apr 25 '19 at 08:56
-
You didn't even bother to paste the error in Google, because there's like 10 different links to SO with answers to that question – mag_zbc Apr 25 '19 at 09:00
2 Answers
localData
is nil, so you are force unwrapping localData
(as a logInResponse
) illegally.
If your optional chaining finds nil
at any point (for example your userData
doesn't exist in UserDefaults
/ has the wrong type) then it won't execute.
You are declaring this doGetLocalDataUser()
function to return a non optional logInResponse
type and force unwrapping a nil
value to try and retrieve one. Best practice is to avoid the force unwrap "bang" operator "!
" because it can lead to fatal errors like this.
Simple solution is to change your method to return an optional logInResponse?
type, and eliminate the bang operator:
func doGetLocalDataUser() -> logInResponse? {
if let userData = UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA), let user = try? JSONDecoder().decode(logInResponse.self ,from: userData){
return user
} else {
return nil
}
}

- 984
- 1
- 12
- 22
I would change the method to this:
func doGetLocalDataUser() -> logInResponse? {
guard let userData = UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA), let user = try? JSONDecoder().decode(logInResponse.self ,from: userData) else {
return nil
}
return user
}
Keep in mind JSON decoding can fail (maybe has wrong format), therefore user will be nil, and this method can return nil

- 412
- 1
- 4
- 14