๐Ÿ“ฑ App Development Study/iOS๐ŸŽ

[Udemy iOS & Swift Bootcamp] Computed Property(์—ฐ์‚ฐ ํ”„๋กœํผํ‹ฐ)

ibelieveinme 2023. 5. 7. 17:16
728x90

*Computed Property: ๋‹ค๋ฅธ ์†์„ฑ ๊ฐ’์œผ๋กœ ํ•ด๋‹น ์†์„ฑ์˜ ๊ฐ’์„ ์ •์˜ํ•˜๋Š” ๊ฒƒ.

 

์•„๋ž˜ condition ID ๊ฐ’์œผ๋กœ  condition Name์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค. ์ด ๋•Œ, condition Name์„ ๋ฐ˜ํ™˜ํ•˜๋ ค๋ฉด weatherData๋ฅผ ์„ ์–ธ ํ›„ ํ•จ์ˆ˜๋กœ ์ ‘๊ทผํ•ด์•ผํ•  ๊ฒƒ์ด๋‹ค.

 

์ด ๋ถ€๋ถ„์„ computed Property๋กœ ๋ฐ”๊พธ๋ฉด watherData ์„ ์–ธ ์ฆ‰์‹œ condition Name์˜ ๊ฐ’๋„ ์„ ์–ธ๋˜์–ด ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์ฐธ๊ณ ๋กœ ๊ทธ๋ƒฅ ์„ ์–ธํ•œ conditionId, cityName ๊ฐ™์€ stored Property๋Š” ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์„ ์ฐจ์ง€ํ•˜์ง€๋งŒ, computed Property๋Š” ์ €์žฅ๊ณต๊ฐ„์„ ์ฐจ์ง€ ํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋˜ ๊ณ„์† ๊ฐ’์ด ๋‹ฌ๋ผ์ง€๋ฏ€๋กœ var ํ˜•์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค.

 

import Foundation

struct WeatherModel{
    let conditionId: Int
    let cityName: String
    let temperature: Double

    func getWeatherConditionName(id: Int) -> String {
       switch id {
       case 200...232:
           return "cloud.bolt"
       case 300...321:
           return "cloud.drizzle"
       case 500...531:
           return "cloud.rain"
       case 600...622:
           return "cloud.snow"
       case 701...781:
           return "cloud.fog"
       case 800:
           return "sun.max"
       case 801...804:
           return "cloud.bolt"
       default:
           return ""
       }
   }
}

 

[Computed Property ์ ์šฉํ•œ ์ฝ”๋“œ]

import Foundation

struct WeatherModel{
    let conditionId: Int
    let cityName: String
    let temperature: Double
    
    var conditionName: String{
        switch conditionId {
        case 200...232:
            return "cloud.bolt"
        case 300...321:
            return "cloud.drizzle"
        case 500...531:
            return "cloud.rain"
        case 600...622:
            return "cloud.snow"
        case 701...781:
            return "cloud.fog"
        case 800:
            return "sun.max"
        case 801...804:
            return "cloud.bolt"
        default:
            return ""
        }
    }
 
}

conditionName ์„ ์–ธ ํ›„ conditionName ๋ฐ˜ํ™˜ ํ•จ์ˆ˜๋ฅผ ๋ณ€์ˆ˜์— ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

728x90