iOS π/Swift
Swift17 - assert/guard
yongmin.Lee
2021. 2. 10. 16:17
assert(_:_:file:line:)
func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line)
Use this function for internal sanity checks that are active during testing but do not impact performance of shipping code.
assert ν¨μ
- assert(_:_:file:line:) ν¨μλ₯Ό μ¬μ©ν©λλ€.
- assert ν¨μλ λλ²κΉ λͺ¨λμμλ§ λμν©λλ€.
- λ°°ν¬νλ μ ν리μΌμ΄μ μμλ μ μΈλ©λλ€.
- μμνλ 쑰건μ κ²μ¦μ μνμ¬ μ¬μ©ν©λλ€
func functionWithAssert(age: Int?) {
assert(age != nil, "age == nil")
assert((age! >= 0) && (age! <= 130), "λμ΄κ° μ
λ ₯μ΄ μλͺ»λμμ΅λλ€")
print("λΉμ μ λμ΄λ \(age!)μΈμ
λλ€")
}
functionWithAssert(age: 50) // "λΉμ μ λμ΄λ 50μΈμ
λλ€"
//functionWithAssert(age: -1) // ERROR! : Assertion failed: λμ΄κ° μ
λ ₯μ΄ μλͺ»λμμ΅λλ€
//functionWithAssert(age: nil) // ERROR! : Assertion failed: age == nil
Guard Statement
A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
guarꡬ문
- guardλ₯Ό μ¬μ©νμ¬ μλͺ»λ κ°μ μ λ¬ μ νΉμ μ€νꡬ문μ λΉ λ₯΄κ² μ’ λ£ν©λλ€.
- λλ²κΉ λͺ¨λ λΏλ§ μλλΌ μ΄λ€ 쑰건μμλ λμν©λλ€.
- guardμ else λΈλ λ΄λΆμλ νΉμ μ½λλΈλμ μ’ λ£νλ μ§μμ΄(return, break λ±)κ° κΌ μμ΄μΌ ν©λλ€.
- νμ μΊμ€ν , μ΅μ λκ³Όλ μμ£Ό μ¬μ©λ©λλ€.
- κ·Έ μΈμλ λ¨μ 쑰건 νλ¨ ν λΉ λ₯΄κ² μ’ λ£ν λλ μ©μ΄ν©λλ€.
func someFunction(info: [String: Any]) {
guard let name = info["name"] as? String else {
return
}
guard let age = info["age"] as? Int, age >= 0 else {
return
}
print("\(name): \(age)")
}
someFunction(info: ["name": "jenny", "age": "10"])
someFunction(info: ["name": "mike"])
someFunction(info: ["name": "yagom", "age": 10]) // yagom: 10