I would like to know is there big difference between
if let error = error{} vs if error != nil? Or is it just how people are different, like how they express themselves in code?
For example if I take this code:
user?.delete { error in
if let error = error {
print(error)
} else {
}
Because I can do the same like this and the output is the same:
user?.delete { error in
if error != nil {
print(error)
}else{
}
The only difference I can see other than "people are different" is that if I do not print error it would be better to use if error != nil because otherwise it would be declaring variable you do not use. Am I right?
As you already recognized at the end of your question, I would agree with you, that I would use if let, if I want to use the error variable to print it out for example. If I would just check if it's not nil and don't need the error variable, I would use if error != nil. You could also do if let _ = error, which is the same as if error != nil as Eric Aya mentioned in the comments of your question
Related
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 = ""
}
I got confused error handling in swift3. I try to do like "if XX function got error then try YY function"
Let me show you what I try:
class MyClass {
enum error: Error
{
case nilString
}
func findURL() {
do {
let opt = try HTTP.GET(url_adr!)
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
do
{
/* This is func1. and got error. I want to if this function has error then go next function. */
try self.stringOperation(data: response.description)
}
catch{
print("doesn't work on func1. trying 2nd func")
self.stringOperation2(data:response.descritption)
}
}
} catch let error {
print("got an error creating the request: \(error)")
}
}
func stringOperation(data:String)throws -> Bool{
do{
/** 1 **/
if let _:String = try! data.substring(from: data.index(of: "var sources2")!){
print("its done")
}else{
throw error.nilString
}
IN 1: I got this fatal error on this line:
"fatal error: unexpectedly found nil while unwrapping an Optional value" and program crashed.
I googled error handling try to understand and apply to in my code. However not succeed yet. Can someone explain where did I wrong?
Additional info: I got String extension for .substring(from:...) , and .index(of:"str"). So these lines doesn't got you confused.
As a general rule, try avoiding using force unwrapping (!), where you have
if let _: String= try! data.substring...
Instead use
if let index = data.index(of: "var sources2"),
let _: String = try? data.substring(from: index) { ... } else { ... }
That way you remove the two force unwraps that may be causing your crash. You already have the if let protection for catching the nil value, so you can make the most of it by using the conditional unwrapping.
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
}
I've been looking up how to use the guard keyword in Swift. Recently a developer told me that the code below will print "success" if there's no error in the closure.
for attachment in attachments! {
attachment.fetchData { (data, error) in
guard let error = error else {
print(“success”)
return
}
print(error.localizedDescription)
}
I'm a bit confused by his statement. After reading the closure and guard keyword documentation from Apple, it looks to me like his code will print out "success" only when there is an error.
I feel like he's using it in reverse, but I may be wrong. Can someone break it down for me and explain if success is printed when there is or is not an error?
Thank you.
The use of guard to unwrap the error is very misleading. You should use it to unwrap your data and make sure there is no error and provide an early exit to your method in case of error.
Just change your guard statement to:
guard let data = data, error == nil else {
print(error ?? "")
return
}
I have the following statement:
func sessionStateChanged(session:FBSession, state:FBSessionState, error:NSError?) {
// If the session was opened successfully
if error == nil && state == FBSessionStateOpen {
println("Session opened");
}
}
which has the following error on the line of the if-statement:
Type NSError? does not conform to protocol '_RawOptionSetType'
However if I remove the second condition, so the code reads:
if error == nil {
println("Session opened");
}
There is no error. This leads me to believe tat the NSError? type is not the issue and that it has something to do with the multiple conditions.
One way to get clearer error messages might be to start a new if statement inside the first rather than combining with && .