How to write Swift error handling
To check when you forget
-Whether the variable name setting is appropriate -Properly implement class responsibilities -Whether the access modifier is appropriate
・ Set a discount rate (DiscountPercentage) for the product -Output an error when the discount rate is not set properly
import Foundation
enum ProductError: Error {
case discountRateIsOverHundret
case discountRateIsZero
case discountRateIsMinus
var description:String {
switch self {
case .discountRateIsOverHundret: return "Discount rate is 100%that's all"
case .discountRateIsZero: return "Discount rate is 0%is"
case .discountRateIsMinus: return "The discount rate is negative"
}
}
}
class Product {
private var name:String
private var price:Double
private var memo:String
init(name:String, price:Double, memo:String){
self.name = name
self.price = price
self.memo = memo
}
public func getName() -> String { name }
public func getPrice() -> Double { price }
public func getMemo() -> String { memo }
public func getInfo(discountPercentage:Double) {
do {
try print("\(self.getName())Discounted price:\(self.getDiscountedPrice(discountPercentage:discountPercentage))Circle")
} catch {
let error = error as! ProductError
print("\(self.getName())Check the discount rate settings:\(error.description)")
}
}
public func getDiscountedPrice(discountPercentage:Double) throws -> Int {
if discountPercentage == 0 { throw ProductError.discountRateIsZero }
if discountPercentage >= 100 { throw ProductError.discountRateIsOverHundret }
if discountPercentage < 0 { throw ProductError.discountRateIsMinus }
let discountRate:Double = (100 - discountPercentage) / 100
return Int(price * discountRate)
}
}
var product1 = Product(name:"Product 1",price:1000,memo:"Sales No.1")
product1.getInfo(discountPercentage:50)
var product2 = Product(name:"Product 2",price:1000,memo:"Can be stored at room temperature")
product2.getInfo(discountPercentage:0)
var product3 = Product(name:"Product 3",price:1000,memo:"Frozen product")
product3.getInfo(discountPercentage:100)
var product4 = Product(name:"Product 4",price:1000,memo:"Attention to us")
product4.getInfo(discountPercentage:-1)
Product 1 Discounted price: 500 yen
Product 2 Check the discount rate setting: The discount rate is 0%is
Product 3 Check the discount rate setting: Discount rate is 100%that's all
Product 4 Check the discount rate setting: The discount rate is negative
Recommended Posts