Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create non-optional in guard to test guarded condition [duplicate]

Tags:

swift

guard

I currently have a function like this...

// this is a property
var currentString: String = ""

func doSomething() {
    let newString: String = goGetANewString()

    guard newString != currentString else {
        return
    }

    currentString = newString
}

But I find it a bit odd that I am creating the newString outside of the guard.

If I move it into the guard then it complains that it needs to be optional.

Is there a way of creating that newString inside the guard statement and checking the condition?

Ideally I'd like something like this, but like I said, it doesn't work this way.

func doSomething() {
    guard let newString: String = goGetANewString(), newString != currentString else {
        return
    }

    currentString = newString
}
like image 798
Fogmeister Avatar asked Jan 31 '18 13:01

Fogmeister


People also ask

What is the guard condition in Swift optionals?

That is, the guard condition is true only if both conditions are true. While working with Swift Optionals, the guard statement is used as the guard-let statement. For example, In the above example, we have created an optional variable named age. Here, we are using the guard-let statement to check whether age contains a value or not.

What is the difference between if and guard statements in C++?

The guard statement is similar to the if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met. guard expression else { // statements // control statement: return, break, continue or throw. } Here, expression returns either true or false.

How do I create an exploit guard configuration item?

On the Home tab, in the Create group, click Create Exploit Policy. On the General page of the Create Configuration Item Wizard, specify a name, and optional description for the configuration item. Next, select the Exploit Guard components you want to manage with this policy. For each component you select, you can then configure additional details.

Should I use guard or notnull when compiling an expression tree?

Although compiling an expression tree is an expensive operation, it is a convenient alternative that can be used in applications that are not performance-critical. With Guard, if you want to guard an argument against null or max length, you just write NotNull and MaxLength and that's it.


1 Answers

The "trick" is to use guard case with a value-binding pattern for the assignment:

func doSomething() {
    guard case let newString = goGetANewString(), newString != currentString else {
        return
    }

    currentString = newString
}
like image 77
Martin R Avatar answered Oct 16 '22 22:10

Martin R