๋ถ„๊ธฐ์— ๋”ฐ๋ผ ๊ฐ’์ด ๊ฒฐ์ •๋˜๋Š” ์ฝ”๋“œ๋ฅผ ์งค ๋•Œ, ๋ณ€์ˆ˜๋ฅผ ๋ฌด์—‡์œผ๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„๊นŒ? ์ž‘์€ ๋ถ€๋ถ„์ด๋‚˜ ์ข‹์€ ์ง€์ ์ด๋ผ ์ƒ๊ฐํ•˜์—ฌ ์ •๋ฆฌํ•ด๋ณธ๋‹ค.

ํ•ต์‹ฌ ์š”์•ฝ

๋ถ„๊ธฐ์— ๋”ฐ๋ผ ๊ฐ’์ด ๊ฒฐ์ •๋  ๋•Œ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค๋ฉด, var๋ณด๋‹ค๋Š” let์„ ์šฐ์„ ์ ์œผ๋กœ ๊ฒ€ํ† ํ•ด๋ณด์ž.

let, var

  • ์ฝ”๋“œ๋ฅผ ์งœ๋‹ค๋ณด๋ฉด, ํŠน์ • ๋ถ„๊ธฐ์— ๋”ฐ๋ผ ๊ฒฐ๊ณผ๋ฅผ ๋‹ค๋ฅด๊ฒŒ ์„ธํŒ…ํ•ด์•ผํ•  ๋•Œ๊ฐ€ ์žˆ๋‹ค.
  • ์ด๋Ÿฐ ๊ฒฝ์šฐ ์•„๋ฌด ์ƒ๊ฐ์—†์ด ์ง ๋‹ค๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์งœ๊ธฐ ์‰ฝ๋‹ค.
internal func calculateResult() -> String {
    var result = ""
    switch type {
    case .a:
        result = "A ํƒ€์ž…์ž…๋‹ˆ๋‹ค."   
    case .b:
        result = "B ํƒ€์ž…์ž…๋‹ˆ๋‹ค."
    case .c:
        result = "C ํƒ€์ž…์ž…๋‹ˆ๋‹ค."
    }
 
    return result
}
  • ํ•ด๋‹น ์ฝ”๋“œ๋Š” ๋ฌธ์ œ ์—†์ด ์ž‘๋™ํ•  ๊ฒƒ์ด๋‹ค.
  • ํ•˜์ง€๋งŒ, result ๋ณ€์ˆ˜์˜ ์„ ์–ธ ๋ถ€์—์„œ var๋กœ ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์—, ์•ฝ๊ฐ„์˜ ํ‘œํ˜„๋ ฅ์ด ๋–จ์–ด์ง€๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋‚ณ๋Š”๋‹ค.
internal func calculateResult() -> String {
    let result: String
    switch type {
    case .a:
        result = "A ํƒ€์ž…์ž…๋‹ˆ๋‹ค."   
    case .b:
        result = "B ํƒ€์ž…์ž…๋‹ˆ๋‹ค."
    case .c:
        result = "C ํƒ€์ž…์ž…๋‹ˆ๋‹ค."
    }
 
    return result
}
  • ๋‹ค์Œ๊ณผ ๊ฐ™์ด let์œผ๋กœ ์„ ์–ธํ–ˆ๋‹ค๋ฉด, โ€œ์•„ ํ•ด๋‹น ๊ฒฐ๊ณผ๊ฐ€ ํ•œ๋ฒˆ๋งŒ ์„ธํŒ…๋˜๋Š” ๊ตฌ๋‚˜โ€์™€ ๊ฐ™์€ ์ถ”๊ฐ€ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.
  • ์ฆ‰, ์กฐ๊ธˆ๋” ์ข‹์€ ํ‘œํ˜„๋ ฅ์„ ๊ฐ–๋Š”๋‹ค.