Search code examples
swiftguard

Create non-optional in guard to test guarded condition


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
}

Solution

  • 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
    }