Detailed explanation and use of swift guard keyword
Swift provides guard keyword, which can simplify cumbersome 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 above code uses the guard keyword to simplify the code style
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 it can help you. Thank you for your support for this site!