내가 원하는 에러를 직접 만들어 throw 로 해당 에러를 받을 수 있다

enum Errors: Error {
   case OutOfStock
}
struct Stock {
   var totalLamps = 5
   mutating func sold(amount: Int) throws {
      if amount > totalLamps {
         throw Errors.OutOfStock
      } else {
         totalLamps = totalLamps - amount
      }
   }
}
var mystock = Stock()

 

이제 throws 함수를 만들었으면 해당 throw된 error를 받을 수 있어야한다. 아래 do-catch 로 error를 처리할 수 있다.

 

하지만 catch Errors.OutOfStock 와 다르게 그냥 catch 문만 써서 간결하게 만들수도 있다.

 

위처럼 만들어 error를 catch 하는 방법도 있고 애초에 에러를 throw 하지 않도록 만드는 방법도 있다.

 

 

Results

error 을 반환하는 대신 더 많은 정보를 반환해야할 때가 있다. 이런 목적으로 Swift 표준 라이브러리는 Result enum을 정의하였다, 이 enum은 success와 failure 2가지 경우를 정의한다. enumeration은 제너릭으로 우리가 지정한 타입으로 만들 수 있다.

다음은 Result<Int, Errors> 으로 success 인 경우 Int를 반환하고 failure 인 경우 Errors를 반환하도록 한다

enum Errors: Error {
   case OutOfStock
}
struct Stock {
   var totalLamps = 5

   mutating func sold(amount: Int) -> Result<Int, Errors> {
      if amount > totalLamps {
         return .failure(.OutOfStock)
      } else {
         totalLamps = totalLamps - amount
         return .success(totalLamps)
      }
   }
}
var mystock = Stock()

let result = mystock.sold(amount: 3)
switch result {
   case .success(let stock):
      print("Lamps in stock: \(stock)")
   case .failure(let error):
      if error == .OutOfStock {
         print("Error: Out of Stock")
      } else {
         print("Error")
      }
}

 

'SwiftUI' 카테고리의 다른 글

App Storage  (0) 2023.11.07
CryptoKit in SwiftUI - 비밀번호 암호화  (0) 2023.11.07
Image Renderer  (0) 2023.11.07
Effect (scaleEffect, rotation3DEffect)  (0) 2023.11.06
animations  (0) 2023.11.06
ytw_developer