unexpectedly found nil while unwrapping an Optional value while reading from DS with fromCString - swift

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 = ""
}

Related

How to read null values from SQLite database using Swfit [duplicate]

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 = ""
}

please give me some solution to this error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value [duplicate]

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
}
}

Should we do nil check for non-optional variables?

I have a function (abc) as follows and I should throw an error when the arguments passed are empty or nil, should I check for nil too or only empty is enough?
public func abc(forURL serviceUrl:String,serviceID:String, error:inout Error? )throws ->[AnyHashable : Any]{
guard serviceUrl != nil, !serviceUrl.isEmpty else {
let argError:Error = MapError.emptyArgumentUrl.error()
error = argError
throw argError
}
guard !serviceID.isEmpty else {
let argError:Error = MapError.emptyArgumentServiceId.error()
error = argError
throw argError
}
serviceID is not an optional.
That means it can't be nil.
So no, there is no need for that check.

getting "unexpectedly found nil" AFTER performing nil check

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
}

Swift 3 better way to unwrap an optional

Right now I have some code that looks like the following:
let msg: String? = myStr.removingPercentEncoding ?? nil
print("msg \(msg!)")
I really don't like the use of ! in msg! as that can possibly throw an exception, I believe.
What's the best way to call myStr.removingPercentEncoding if myStr is not nil and then unwrap msg without throwing an exception?
The proper way would be:
if let msg = myStr.removingPercentEncoding {
print("msg \(msg)")
}
Here, msg is only valid inside the if statement and only if myStr.removingPercentEncoding isn't nil.
If you wish to print something if myStr.removingPercentEncoding is nil, then you could and an else:
if let msg = myStr.removingPercentEncoding {
print("msg \(msg)")
} else {
print("msg has no value")
}
Read up on Optional Binding in the The Swift Programming Language book.
This line is completely useless, when myStr.removingPercentEncoding is nil, then nil (right hand side of ??) is assigned to msg:
let msg: String? = myStr.removingPercentEncoding ?? nil
Why don't you make it as:
let msg: String = myStr.removingPercentEncoding ?? ""
print("msg \(msg)")