Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using guard with a non-optional value assignment

Tags:

swift

This is not a question about optional arrays, as one can see in the answers.

I like using guard because it makes your intensions clear. I've used it both for the optional version like this...

guard let c = MyOptionalArray else { return }

as well as for more traditional bounds checking on non-optionals...

guard MyArray.count > 0 else { return }

But now I'd like to use that count in following code. So I did...

guard let c = MyArray.count > 0 else { return }

which doesn't work, obviously, so I did what should...

guard let c = parts.count where c > 1 else { return }

But that says Initializer for conditional binding must have Optional type, not 'Int'. Now I understand the error, and tried a bunch of seemingly obvious changes to the format, but no go. Is there no way to use guard as an assignment on a non-optional value? This seems like something it should be able to do.

like image 897
Maury Markowitz Avatar asked Feb 15 '16 17:02

Maury Markowitz


People also ask

When to use if let and guard?

In if let , the defined let variables are available within the scope of that if condition but not in else condition or even below that. In guard let , the defined let variables are not available in the else condition but after that, it's available throughout till the function ends or anything.

What is difference between guard and if let in Swift?

With guard let you are creating a new variable that will exist in the current scope. With if let you're only creating a new variable inside the code block.

How does guard let work?

Swift gives us an alternative to if let called guard let , which also unwraps optionals if they contain a value, but works slightly differently: guard let is designed to exit the current function, loop, or condition if the check fails, so any values you unwrap using it will stay around after the check.

Why we use guard let in Swift?

In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met. 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.


1 Answers

If you throw a case in there, it'll work. So as follows:

guard case let c = parts.count where c > 1 else { return }
like image 103
Gavin Avatar answered Oct 12 '22 15:10

Gavin