iOS/iOS Swift Udemy - AngelaYu

Sec13 152) 함수 리팩토링 (computed property)

Developer-Michelle 2023. 1. 1. 17:28

Udemy Angela Yu 강의 내용 중 --

 

computed property

var aProperty: Int {

   return 2+5 

}

 

결국 aProperty는 2+5와 같음.


응용: Clima 프로젝트 중

struct WeatherModel {

    let conditionId: Int

    let cityName: String

    let temperature: Double

    

    //소수점 한자리까지만 표시

    var temperatureString: String {

        return String(format: "%1f", temperature)

    }

}

 

WeatherManager.swift 파일 내에서

 let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)

print(weather.temperatureString) => 이런식으로 사용

 


WeatherManager.swift 파일 내에서

let weather.= WeatherModel(conditionId: id, cityName: name, temperatue: temp)

print(weather.getConditionName(weatherId: id)) 이런식으로 쓰던거를 간단하게

-> print(weather.conditionName)으로 쓸 수 있게 하는 방법? 아래와 같이 WeatherModel에서 적으면 됨.

 

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 "cloud"

        }

    }

 

해당 함수는 원래 아래와 같이 적었었음.

func getConditionName(weatherId: Int) -> String {

  switch weatherId {

  case 200...232:

   return "cloud.bolt"

.... 

}

    

 


참고:

https://onelife2live.tistory.com/17

 

[Swift] Computed Property 는 언제 쓰는지 알아보자

Computed Property를 직역하면 계산된 속성이 됩니다. 하지만 수학적 계산이 실행된다는 의미는 아닙니다. 다른 속성을 기반으로 해당 속성 값이 결정된다는 의미입니다. 저장 속성(Stored Property)은 값

onelife2live.tistory.com