Questions tagged [guard-statement]

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

guard is a conditional statement that requires execution to exit the current block if the condition isn’t met.

Syntax:

guard <condition> else {
    <statements>
}

The value of any condition in a guard statement must have a type that conforms to the BooleanType protocol, it can also be an optional binding declaration.

Any constants or variables assigned a value from an optional binding declaration in a guard statement condition can be used for the rest of the guard statement’s enclosing scope.

For example:

guard let value = someOptional else {
     // someOptional is nil, value is not accessible
     return
}

// do something with the value
// value is available here
42 questions
203
votes
13 answers

Swift's guard keyword

Swift 2 introduced the guard keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates an submitTapped function: func submitTapped() { guard username.text.characters.count >…
David Snabel
  • 9,801
  • 6
  • 21
  • 29
41
votes
3 answers

Swift error: guard body must not fall through

I have the following guard statement, which is producing an error. What's wrong? guard NSFileManager.defaultManager().fileExistsAtPath(appBundlePath) else { print("App bundle doesn't exist") } error: 'guard' body may not fall through error:…
James Alvarez
  • 7,159
  • 6
  • 31
  • 46
7
votes
1 answer

Guard when setting multiple class properties in Swift 2

It's trivial enough to do something like this: class Collection { init(json: [String: AnyObject]){ guard let id = json["id"] as? Int, name = json["name"] as? String else { print("Oh noes, bad JSON!") return …
Leah Sapan
  • 3,621
  • 7
  • 33
  • 57
6
votes
1 answer

How to use guard outside of function?

Is it possible to use guard outside of a function? The following throws an error that return or break needs to be used but that isn't possible in this case. var var1 = String?() guard let validVar = var1 else { print("not nil") }
4thSpace
  • 43,672
  • 97
  • 296
  • 475
5
votes
1 answer

Swift: make debugging easier by being able to catch return value in defer statement

So I love declaring variables to hold return value and then return said variable on next line, thus making it easy to debug my code, I can just set a breakpoint at the return line and see what value it returns. I use this everywhere and it makes all…
Sajjon
  • 8,938
  • 5
  • 60
  • 94
4
votes
1 answer

Understanding the guard function and list comprehension

I am learning about the guard function from the book 'Learn You a Haskell for Great Good!' by Miran Lipovaca. For the following example: ghci> [1..50] >>= (\x -> guard('7' `elem` show x) >> return x) [7, 17, 27, 37, 47] I know that guard takes a…
ceno980
  • 2,003
  • 1
  • 19
  • 37
4
votes
2 answers

Why guards are called 'guards'?

Does anyone know what is the origin of the name for the construct called guards? func x | cond1 -> expr1 ... | condN -> exprN Wikipedia article Guard_(computer_science) gives some historical perspective, but lacks explanation for…
3
votes
2 answers

Using assert in the else block of guard statement

I came across this in the implementation instructions of Google Analytics: guard let gai = GAI.sharedInstance() else { assert(false, "Google Analytics not configured correctly") } I had never thought it was possible to have an assertion in the…
Drew
  • 674
  • 5
  • 14
3
votes
1 answer

guard statement inconsistencies

// Doing let first followed by a bool check in guard statement results in compilation error self.action = { [weak self] in guard let `self` = self, data.isJSON() else { return } // Doing bool check first and then let works self.action =…
Boon
  • 40,656
  • 60
  • 209
  • 315
3
votes
1 answer

returning a value from do statement in a guards haskell

I'm trying to find if some letter is already used in any string in the list of strings. If yes - choose next letter to compare. If no - return this letter and update the initial list. To check in the list I'm using: check:: [String] -> Char ->…
Olenka
  • 259
  • 3
  • 12
3
votes
1 answer

Why does guard let x = x exhibit different scope behavior?

Why does guard let x = x inside a method behave differently than outside? Example code below is copied right out of Playground. var x:Int? = 3 func foo(x: Int?) { guard let x = x else { return } print(x) // print…
Boon
  • 40,656
  • 60
  • 209
  • 315
2
votes
2 answers

guard let error: Initializer for conditional binding must have Optional type not 'String'

I got fatal error While using guard let. Here's the error: Initializer for conditional binding must have Optional type not 'String' Below my code which i have used: @IBAction func signUpButtonPressed(sender: UIButton) { guard let email =…
Anuar Maratkhan
  • 325
  • 5
  • 21
2
votes
2 answers

Swift 2.0 guard giving me errors

I was using the guard function and when I'd typed the guard statement below: var IOUArray = [IOU(amount: 20, payer: "Isabella", description: "test"),IOU(amount: 30, payer: "Dad", description: "Test2")] NSKeyedArchiver.archiveRootObject(IOUArray,…
needshelp
  • 595
  • 1
  • 6
  • 25
2
votes
1 answer

Why doesn't guard create unwrapped var?

Why do I need to unwrap the variable unwrapped in the final return statement? Isn't guard supposed to handle this? func test() -> String { let fmt = NSNumberFormatter() let myValue:Double? = 9.50 guard let unwrapped = myValue else { …
4thSpace
  • 43,672
  • 97
  • 296
  • 475
2
votes
2 answers

Swift 1.2 to 2.0 conversion - guard vs if let

I am trying to convert some code from Swift 1.2 to 2.0. I have the below code in Swift 1.2 //enable OR disable keys. if(discountAmountTextField.text.isEmpty){ keypadView.disableNotRequiredKeys() }else{ …
tbag
  • 1,268
  • 2
  • 16
  • 34
1
2 3