This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
im having this problem: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
is there any way to solve it?
this is my code:
let ref = Database.database().reference()
ref.child("ChildA").child("Title").observeSingleEvent(of: .value, with: { DataSnapshot in
print(DataSnapshot) // replace this with textLabel or other item
let m = DataSnapshot.value as? String
self.TitleA.text = m //Error in this line
})
Replace:
self.TitleA.text = m
With this:
self.TitleA?.text = m ?? ""
Related
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 3 years ago.
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!
}
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
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
}
}
Despite checking for nil, I am getting fatal error: unexpectedly found nil while unwrapping an Optional value the error is being caught in the conditional (first line below)
if (obj.prop != nil && obj.prop?.otherprop != nil) {
anotherObj.yetanotherprop = (obj.prop?.otherprop as NSURL).absoluteString
}
I have also tried this with if let as follows (xcode highlights the 2nd let as being where the unexpected nil is found):
if let objA = obj.prop,
let otherProp = objA.otherPROP {
anotherObj.yetanotherprop = (otherProp as NSURL).absoluteString
}
Why don't either of these work?!
I am getting the source object (obj in both cases above) from a 3rd party library that is written in objective c. I am suspecting that I am checking for nil wrong somehow?
So in writing this up I think I sort of figured it out. I don't knwo why the first one doesn't work, but the second works as:
if let objA = obj.prop,
let otherProp = objA?.otherPROP {
anotherObj.yetanotherprop = (otherProp as NSURL).absoluteString
}
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I got access error('fatal error: unexpectedly found nil while unwrapping an Optional value') when print variable p02. According to the error message, I still cannot understand the reason.
var p02:Person! = nil
var p03:Person? = nil
if (p02==nil)
{
print("p02 is nil")
}
if (p03==nil)
{
print("p03 is nil")
}
print(p03)
print(p02)
Anyone know why,
Thanks
cause it always tries to print p02 and p03 even if they are nil
try this
var p02:Person! = nil
var p03:Person? = nil
if (p02==nil)
{
print("p02 is nil")
}else{
print(p02)
}
if (p03==nil)
{
print("p03 is nil")
}else{
print(p03)
}
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I'm trying to send a saved string to the apple watch with WCsession methode. But when I do this I get an error in swift 2.3: fatal error: unexpectedly found nil while unwrapping an optional value !!
func Reloadip() {
let ip = nsdefauts.object(forKey: saved)
let requestValues = ["send" : "A" , "IP" : ip as! String ]
print(requestValues)
if(WCSession.isSupported()){
session!.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
print("sended ip")
}
}
the error is made at the "ip as! String line" how can I fix this. ?
regards Quinn
You should use more safe code instead
func Reloadip() {
guard let ip = nsdefauts.objectForKey(saved) as? String else {
print("there is no saved ip")
return
}
let requestValues = ["send" : "A" , "IP" : ip]
print(requestValues)
if(WCSession.isSupported()){
session?.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
print("sended ip")
}
}
I am reading from a dbtable and get an error at a specific position of the table. My sql is ok, because I could already read from the same table, but at a specific row I get an error and I would like to know howto handle this error. I am not looking for a solution to solve my db-issue, I am just looking for handling the error, so it doesn't crash.
I have the following code :
let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
if unsafepointer != nil {
sText=String.fromCString(unsafepointer)! // <<<<<< ERROR
} else {
sText="unsafe text pointer is nil !";
}
I get an error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
at line marked with <<<<<< ERROR.
The unsafe pointer's value is not nil:
pointerValue : 2068355072
How can I handle this error, so my app is not crashing ?
Another possible solution is this:
let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
var sText = "unsafe text pointer is nil !";
if unsafepointer != nil{
if let text = String.fromCString(unsafepointer) as String?{
sText = text;
}
}
let statementValue = sqlite3_column_text(statement, 2)
var sText = withUnsafeMutablePointer(&statementValue) {UnsafeMutablePointer<Void>($0)}
if sqlite3_column_text(statement, 2) != nil {
print("do something")
} else {
YourString = ""
}