Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Computed property vs method 구분 본문

iOS 기본 (swift)

[iOS - swift] Computed property vs method 구분

jake-kim 2021. 7. 25. 23:18

Compueted Property

  • Concept: 객체의 다른 property가 변경 될 수 없고, 다른 속성이 변경되지 않으면 다른 시간에 계산된 property 값은 동일한 출력을 제공
  • 시간 복잡도가 O(1)
  • 어떤 예외도 throw하지 않는 경우
  • 계산 비용이 저렴

ex)

struct Point {
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter) {
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
}

Method

  • Conecpt: 객체의 다른 property가 중 업데이트 될 수 있고, 다른 속성이 변경되지 않았을때 다른 시간에 method 반환값은 다른 값이 나올 수 있는 개념
  • O(N) 이상
  • 무거운 작업

ex) 

class Counter {
    var count = 0
    func increment() {
        count += 1
    }
    func increment(by amount: Int) {
        count += amount
    }
    func reset() {
        count = 0
    }
}

결론

  • 가벼운 작업이어나, 객체의 다른 property 값이 변경되지 않으면 Computed property사용
  • 무거운 작업이거나, 객체의 다른 property 값이 변경되면 Method사용

 

* 참고

https://docs.swift.org/swift-book/LanguageGuide/Properties.html

https://docs.swift.org/swift-book/LanguageGuide/Methods.html

https://medium.com/swift-india/functions-vs-computed-property-what-to-use-64bbe2df3916

Comments