swift guard keyword explanation and use
- 2020-06-01 11:08:23
- OfStack
swift guard keyword explanation and use
Swift provides the guard keyword, and the guard keyword simplifies the tedious judgment logic
func buy( money: Int , price: Int , capacity: Int , volume: Int){
if money >= price{
if capacity >= volume{
print("I can buy it!")
print("\(money-price) Yuan left.")
print("\(capacity-volume) cubic meters left")
}
else{
print("No enough capacity")
}
}
else{
print("Not enough money")
}
}
The code above simplifies the code style with the guard keyword
func buy2( money: Int , price: Int , capacity: Int , volume: Int){
guard money >= price else{
print("Not enough money")
return
}
guard capacity >= volume else{
print("Not enough capacity")
return
}
print("\(money-price) Yuan left.")
print("\(capacity-volume) cubic meters left")
}
Thank you for reading, I hope to help you, thank you for your support of this site!