Create non-optional controls to check protected status

I currently have such a function ...

// 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 little strange that I create newStringoutside guard.

If I translate it in guard, then he complains that it should be optional.

Is there a way to create this newStringinside an operator guardand check the condition?

Ideally, I would like something like this, but, as I said, this does not work.

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

    currentString = newString
}
+4
source share
2 answers

"The trick" is to use guard casea value binding template for the destination:

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

    currentString = newString
}
+6
source

Guard let . .

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

    if newstring != currentstring {
    currentstring = newstring
    } }

.

-1

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


All Articles