λ°μν
π λͺ©λ‘
- μλ¬ μ²λ¦¬λ?
- Example
- ν¨μ μμμ μ²λ¦¬
- do try catch
- κ° μ λ¬ λ°κΈ°
π μλ¬ μ²λ¦¬λ?
νλ‘κ·Έλ¨ λ΄μμ μλ¬κ° λ°μν μν©μ λν΄ λμνκ³ μ΄λ₯Ό 볡ꡬνλ κ³Όμ
π Example
μλ¬λ₯Ό λ°μ μν€λ €λ©΄ μ΄λ κ² ν΄μ£Όλ©΄ λ©λλ€.
enum PhoneError: Error {
case unknown
case batteryLow(batteryLevel: Int)
}
throw PhoneError.batteryLow(batteryLevel: 20) // Error!
π ν¨μ μμμ μ²λ¦¬
// throws λ€μλ λ¦¬ν΄ νμ
func checkPhoneBatteryStatus(batteryLevel: Int) throws -> String {
guard batteryLevel != -1 else { throw PhoneError.unknown }
guard batteryLevel >= 20 else { throw PhoneError.batteryLow(batteryLevel: 20) }
return "λ°°ν°λ¦¬ μνκ° μ μ μ
λλ€."
}
π do, catch
func checkPhoneBatteryStatus(batteryLevel: Int) throws -> String {
guard batteryLevel != -1 else { throw PhoneError.unknown }
guard batteryLevel >= 20 else { throw PhoneError.batteryLow(batteryLevel: batteryLevel) }
return "λ°°ν°λ¦¬ μνκ° μ μ μ
λλ€."
}
do {
try checkPhoneBatteryStatus(batteryLevel: 10) // μλ¬κ° λ°μν μ μλ ꡬκ°μ try λ₯Ό μ μ΄μ€λ€
} catch PhoneError.unknown {
print("μμ μλ μλ¬ μ
λλ€.")
} catch PhoneError.batteryLow(let batteryLevel) {
print("λ°°ν°λ¦¬ μ μ λΆμ‘± λ¨μ λ² ν°λ¦¬ : \(batteryLevel)%")
} catch {
print("κ·ΈμΈ μ€λ₯ λ°μ : \(error)") // μ§μ λ³μλ‘ error κ° λμ€κ² λλ€.
}
π κ° μ λ¬ λ°κΈ°
μλ¬κ° λ°μνλ©΄ nill μ λ°κΈ° λ©λλ€.
let status = try? checkPhoneBatteryStatus(batteryLevel: -1)
status // nil
λ°μν
'Swift' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
Swift κ³ μ°¨ν¨μ(map, filter, reduce) (0) | 2021.11.28 |
---|---|
Swift closure (0) | 2021.11.28 |
Swift μ΅μ λ 체μ΄λ (0) | 2021.11.28 |
Swift μ΄κ±°ν (0) | 2021.11.28 |
Swift μ΅μ€ν μ (0) | 2021.11.28 |