Control Flow 중에 하나, Optional Binding에 많이 사용되는 문이라고 한다.
// guard let
func greet(person: [String: String]){
guard let name = person["name"] else {
return
}
print("Hello \(name)")
guard let location = person["location"] else {
return
}
print("Hello \(location)")
if let name = person["name"]{
} else {
}
}
greet(person: ["name": "Johnn", "location": "seoul"])
이렇게 guard 구문으로 control flow가 가능하다. 위에서 구조체에 name이라는 key의 value 값이 존재한다면? guard let 아래문으로 내려가게 된다. 마찬가지로 location이라는 key의 value 값이 존재한다면? guard let 아래 문으로 내려가게 되는 것이다.
if let을 사용한 optional Binding, guard let을 사용한 optional Binding
func fullName(name: String, rawPrefix: String?){
//if let
if let prefix = rawPrefix {
print(prefix+name)
} else {
print("prefix need")
}
//guard let
guard let prefix = rawPrefix else {
print("prefix need")
return
}
print(prefix+name)
}
fullName(name: "dohyun", rawPrefix: "chung")
fullName(name: "dohyun", rawPrefix: nil)
출력
chungdohyun ( if let)
chungdohyun (guard)
prefix need ( if let)
prefix need (guard)
func guardControlFlow() {
let strings: [String] = ["hi", "dohyun", "findout", "guardlet"]
for string in strings{
guard string != "guardlet" else {
continue
// string이 guardlet일때는 아래 수행 아니면 걍 다 재끼고 다시 포문 돌리기
}
print(string)
}
}
guardControlFlow()
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
struct Item{
var price: Int
var count: Int
}
class VendingMachine{
var inventory = [
"Candy Bar" : Item(price:12, count: 7),
"Chips" : Item(price: 10 , count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinDeposited = 0
func vend(itemNamed name: String) throws {
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
guard item.price <= coinDeposited else {
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinDeposited)
}
}
}
func guardletF (string: String?){
guard let string = string else {
return
}
print("string is \(string)")
}
guardletF(string: "test")
func manyGuardLet(first: String?, second: String?, third: String?){
guard let first = first, let second = second, let third = third else {
return
}
print("first is \(first), second is \(second), third \(third)")
}
manyGuardLet(first: "one", second: "two", third: "three") // one two three
manyGuardLet(first: nil, second: "two", third: "three") // X
manyGuardLet(first: "one", second: nil, third: "three") // X
manyGuardLet(first: "one", second: "two", third: nil) // X| [iOS] URLsession으로 API 통신하기 2탄 (0) | 2021.04.28 |
|---|---|
| [iOS] URLsession으로 API 통신하기 1탄 (0) | 2021.04.28 |
| [iOS] 세그웨이 사용법 (0) | 2021.03.22 |
| [swift] 옵셔널 체이닝과 nil coalescing (0) | 2021.03.21 |
| [Swift] 프로퍼티 - 연산프로퍼티(Computed property) (0) | 2021.03.13 |
댓글 영역