This time, I learned about the guard statement, so I will output it.
*** In a nutshell, the guard statement is a conditional branch statement for early exit when conditions are not met. *** *** The basic writing method is as follows.
qiita.rbvar
guard conditional expression else{
Statement executed when the conditional expression is false
Need to leave the scope where the guard statement is written
(That is, you need to write a return)
}
qiita.rbvar
Let's look at a basic example!
func someFunction(){
let value = 99
guard value >= 100 else{
print("Value less than 100")//Executed because the value was less than 100
return
}
someFunction()
Execution result:Value less than 100
As for the guard statement, the guard-let statement can be used in the same way as the if statement.
*** Check the URL below if you want to review the if statement! !! *** *** What is an if statement? ("Https://qiita.com/syunta061689/items/65d54a58936a5849a67a")
The difference from the if-let statement is that variables and constants declared in the guard-let statement can be used after the *** guard-let statement. *** ***
The following example accesses the constant int declared in the guard-let statement.
qiita.rbvar
func someFunction(){
let a: Any = 1 //Any type
guard let int= a as? Int //Can a be downcast to an Int type?
else{//If not, do the following
print("a is not an Int type")
return
}
print("The value is of type Int\(int)is")//int can be used even after the guard statement!
}
someFunction()
Execution result:The value is 1 of type Int.
Now, let's use a concrete example to dig deeper into how to use it properly with if statements. In the following example, the if statement and guard statement receive two Int types, return the sum if they have both values, and return nil if either one does not have a value. I will.
*** If statement example ***
qiita.rbvar
func add(_ optionalA: Int?,_ optionalB: Int?)-> Int?{
let a: Int
if let unwrappedA = optionalA{
a = unwrappedA
}else{
print("There is no value in the first argument")
return nil
}
let b: Int
if let unwrappedB = optionalB{
b = unwrappedB
}else{
print("There is no value in the first argument")
return nil
}
return a+b
}
add(optional(3)optional(2))//5
*** Example of guard statement ***
qiita.rbvar
func add(_ optionalA: Int?, _ optionalB: Int?)-> Int?{
guard let a = optionalA else{
print("There is no value in the first argument")
return nil
}
guard let b = optionalB else{
print("There is no value in the second argument")
return nil
}
return a+b
}
add(Optional(3),Optional(2))//5
In this way, code that exits early depending on the condition is *** simpler to implement using the guard statement *** Also, in the guard statement, if you forget to write the exit process, an error will occur, so you can prevent simple mistakes!
Recommended Posts