Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
}
like image 770
4thSpace Avatar asked Sep 29 '15 04:09

4thSpace


People also ask

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.

How do you use a guard statement?

The syntax of the guard statement is: guard expression else { // statements // control statement: return, break, continue or throw. } Note: We must use return , break , continue or throw to exit from the guard scope.

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.

Can we use guard VAR in Swift?

Guard var is never used in The Swift Programming Language.


1 Answers

No its not possible. To instanciate variables with knowledge of other variables in the class, you can use lazy initialisation or getter.

var testString : String?
lazy var testString2 : String = {
     guard let t = self.testString else { return String()}
      return t
}()

if iam wrong feel free to correct me :)

guard is made for robustness of functions i think, and will do a break in the function if the conditions are wrong. So if you really need this variable it has to be meet the conditions. Like an if let but more clean :)

From your example: var testString = String?() is invalid. Instantiate an String will never be nil so no optional is requiert.

Edit: I wrote an example in my Playground.

import UIKit

var var1 : String?

var validVar : String = {
    guard let validVar = var1 else {
        print("not nil")
        return "NIL"
    }
    return validVar
}()

print("\(validVar)")
like image 113
Björn Ro Avatar answered Oct 22 '22 23:10

Björn Ro