Using protection to check for level zero without implicit deployment

I know that there are similar questions around, but I could not find a single specific problem. I have a request where I want to check for a key error. it is not there, everything is in order, if not, I have to handle the error. Currently, I have implemented it as follows:

if let error = json["error"] {
    // handle error
}
else {
    // handle success
}

I would like to use the guard instruction here so that the success case is not indexed. The only way I came up with is

guard json["error"] == nil else {
    let error = json["error"]!
    // handle error
} 

// handle success

but that seems wrong to me with !. Are there any other approaches to this?

+4
source share
2 answers

In code, guardyou will need to have a return statement in the else block. Like this...

guard json["error"] == nil else {
    let error = json["error"]!
    // handle error
    return
}

// handle success

. .

, . , guard - . if, . else.

if let error = json["error"] {
    print(error)
    // handle error
    return
}

// handle success...
// no need for else block. Just return from the if in the error case.

guard let if let , .

, .

+6

Swift Evolution:

" "

https://forums.swift.org/t/idea-guard-not-let-optional-binding/2614

[] , , , , (, , ), :

guard cachedValue == nil else { return cachedValue! }
  cachedValue = //… expensive calculation

"", let . , . ; .

, Swift.

- / guard, , force-unwrap:

guard json["error"] == nil else {
    return json["error"]!
}

if-let ( -, guard):

if let error = json["error"] {
    return error
}
+1

Source: https://habr.com/ru/post/1667120/


All Articles