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

1

7

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
}
Tache answered 31/1, 2018 at 13:14 Comment(2)
Why does it feel odd to call goGetANewString before guard?Moisesmoishe
@user28434 because I'm only ever using the newString if the guard succeeds. By creating the newString before the guard I then also have access to it inside the else of the guard. Which is fine... if I need it. But in this case I specifically don't.Tache
S
10

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
}
Schroer answered 31/1, 2018 at 13:17 Comment(1)
Thanks! I need to read up more about the different uses of case. I only really know/understand them inside switches.Tache

© 2022 - 2024 — McMap. All rights reserved.