Aug 31, 2021, TIL (Today I Learned) - 이유있게 게을러지자[근거 있는 lazy var 지향하자]

Inwoo Hwang·2021년 8월 31일
0

TIL

목록 보기
3/8
post-thumbnail

학습내용


Lazy var를 무분별하게 사용하면 안되는 이유

lazy란?

lazy 저장 프로퍼티는 사용되기 전까지 값이 계산되지 않는 프로퍼티를 지칭합니다.

NOTE

lazy 프로퍼티는 항상 변수로 선언되어야 합니다. 왜나하면 인스턴스의 초기화가 완료되기 전까지 초기값이 할당되지 않을 수 있기 때문이죠.

lazy 프로퍼티는 특정 인스턴스에 의존적이어서 해당 요소가 끝나기 전까지 적절한 값을 알지 못하는 경우에 유용하게 사용될 수 있습니다. 또한 복잡한 계산 그리고 부하가 많이 걸리는 작업을 지연 프로퍼티로 선언하여 사용하면 실제 사용되기 전까지는 실행되지 않아서 인스턴스의 초기화 시점에 복잡한 계산을 피할 수 있다는 장점을 가지고 있습니다.

여태까지 어떻게 무분별하게 lazy를 사용해 왔는가...

저는 여태까지 lazy를 자세히 모르고...그냥 view를 만들때 해당 view의 모든 프로퍼티를 관리하기 편해서... 클로저를 할당하여 lazy property를 만들어서 사용해 왔습니다. 이렇게요.

		lazy var itemTitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.preferredFont(forTextStyle: .title3)
        label.textAlignment = .center
        label.numberOfLines = 1
        label.translatesAutoresizingMaskIntoConstraints = false
        label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        label.textColor = .black
        return label
    }()
    
    lazy var itemPriceLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.preferredFont(forTextStyle: .body)
        label.textAlignment = .center
        label.numberOfLines = 1
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .black
        return label
    }()
    
    lazy var itemDiscountedPriceLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.preferredFont(forTextStyle: .body)
        label.textAlignment = .center
        label.numberOfLines = 1
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .black
        return label
    }()

등등등....

해당 라벨은 특정 인스턴스에 의존적이지도 않고 부하가 많이 걸리지 않는데도 불구하고 그냥 인터넷에서 쓰이고 뭔가 멋있어 보이니까 과거의 제가 이렇게 작성한 것 같습니다...반성합니다. 거기다 이제 보니 접근제한 또한 적절하지 않아보이네; 그래서 이번 오픈마켓 프로젝트를 다시 진행하면서 이유 없는 lazy var를 다 수정하려 합니다. 😅

[참고]:

What are lazy variables? - free Swift 5.4 example code and tips (hackingwithswift.com)

profile
james, the enthusiastic developer

0개의 댓글