How to use protection outside the function?

Can I use guardout functions?

Then an error message is issued, which should be used to return or break, but in this case this is not possible.

var var1 = String?()
guard let validVar = var1 else {
    print("not nil")
}
+4
source share
1 answer

No, It is Immpossible. To initialize variables by knowing other variables in the class, you can use lazy initialization or getter.

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

If I'm wrong, feel free to fix me :)

protection is made for the reliability of the functions that I think, and will take a break in the function if the conditions are incorrect. Therefore, if you really need this variable, it must meet the conditions. Like let let but cleaner :)

: var testString = String?() . , .

Edit: .

import UIKit

var var1 : String?

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

print("\(validVar)")
+4

Source: https://habr.com/ru/post/1609412/


All Articles