Swift-style-guide: λ§Œμ•½ λŒ€ κ°€λ“œ

에 λ§Œλ“  2018λ…„ 10μ›” 25일  Β·  3μ½”λ©˜νŠΈ  Β·  좜처: raywenderlich/swift-style-guide

ν˜„μž¬ μŠ€νƒ€μΌ κ°€μ΄λ“œλŠ” 쀑첩 if guard μ‚¬μš©μ— λŒ€ν•΄ λͺ…ν™•ν•˜μ§€λ§Œ guard λŒ€μ‹  if λ₯Ό μ‚¬μš©ν•΄μ•Ό ν•˜λŠ” 예λ₯Ό 보여쀄 수 μžˆμŠ΅λ‹ˆλ‹€. ν•„μš”ν•œ μ˜΅μ…˜μ˜ λž˜ν•‘ ν•΄μ œκ°€ μ—†λŠ” 경우:

μš°μ„ μ˜:

if !success { return false }

μ„ ν˜Έν•˜μ§€ μ•ŠμŒ:

guard success else { return false }

여기에 κ°€μž₯ 잘 μ„€λͺ…λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€: https://www.natashatherobot.com/swift-when-to-use-guard-vs-if/

κ°€μž₯ μœ μš©ν•œ λŒ“κΈ€

λ‚˜λŠ” Failing Guards μ„Ήμ…˜μ΄ 이것을 닀루고 μžˆλ‹€κ³  거의 말할 κ²ƒμž…λ‹ˆλ‹€.
Guard statements are required to exit in some way.

...λ˜λŠ” λ‚˜νƒ€μƒ€μ˜ λΈ”λ‘œκ·Έμ—μ„œ λ‹€μŒκ³Ό 같이 λ§ν–ˆμŠ΅λ‹ˆλ‹€.
think of guard as a lightweight Assert

λ”°λΌμ„œ λ‹€μŒμ„ μˆ˜ν–‰ν•΄μ•Ό ν•©λ‹ˆλ‹€.

guard success else { return false }

μ—¬κΈ°μ„œ guard 의 이점은 μ»΄νŒŒμΌλŸ¬κ°€ μ’…λ£Œλ₯Ό 보μž₯ν•œλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€. μ˜ˆμ‹œ:

// This compiles fine and a bug risks going unnoticed
if !success {
  // Some code here
  // Forgot the return statement
}

// Compiler error, you are required to return and the bug is prevented
guard success else {
  // Some code here
  // Forgot the return statement
}

λͺ¨λ“  3 λŒ“κΈ€

λ‚˜λŠ” Failing Guards μ„Ήμ…˜μ΄ 이것을 닀루고 μžˆλ‹€κ³  거의 말할 κ²ƒμž…λ‹ˆλ‹€.
Guard statements are required to exit in some way.

...λ˜λŠ” λ‚˜νƒ€μƒ€μ˜ λΈ”λ‘œκ·Έμ—μ„œ λ‹€μŒκ³Ό 같이 λ§ν–ˆμŠ΅λ‹ˆλ‹€.
think of guard as a lightweight Assert

λ”°λΌμ„œ λ‹€μŒμ„ μˆ˜ν–‰ν•΄μ•Ό ν•©λ‹ˆλ‹€.

guard success else { return false }

μ—¬κΈ°μ„œ guard 의 이점은 μ»΄νŒŒμΌλŸ¬κ°€ μ’…λ£Œλ₯Ό 보μž₯ν•œλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€. μ˜ˆμ‹œ:

// This compiles fine and a bug risks going unnoticed
if !success {
  // Some code here
  // Forgot the return statement
}

// Compiler error, you are required to return and the bug is prevented
guard success else {
  // Some code here
  // Forgot the return statement
}

@RobertGummesson λ”°λΌμ„œ 선택 사항을 풀지 μ•Šμ•„λ„ λ˜λŠ” κ²½μš°μ—λ„ μ’…λ£Œν•΄μ•Ό ν•˜λŠ” 였λ₯˜κ°€ λ°œμƒν•˜λ©΄ guard 보닀 if λ₯Ό μ‚¬μš©ν•˜λŠ” 것이 μ’‹μŠ΅λ‹ˆλ‹€. μ˜³μ€?

@agirault - 예, λ˜λŠ” λ‹¨μˆœνžˆ μ’…λ£Œκ°€ ν•„μš”ν•©λ‹ˆλ‹€(μ‹€νŒ¨λ‘œ μΈν•œ 것인지 여뢀에 관계없이).

이 νŽ˜μ΄μ§€κ°€ 도움이 λ˜μ—ˆλ‚˜μš”?
0 / 5 - 0 λ“±κΈ‰

κ΄€λ ¨ 문제

jackwu95 picture jackwu95  Β·  6μ½”λ©˜νŠΈ

grosch picture grosch  Β·  6μ½”λ©˜νŠΈ

luki picture luki  Β·  3μ½”λ©˜νŠΈ

WingYn picture WingYn  Β·  15μ½”λ©˜νŠΈ

icanzilb picture icanzilb  Β·  6μ½”λ©˜νŠΈ