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