보통 코드로 UI 레이아웃을 작성할때 아래 ‘code1 과 같이 “lazy var”를 선언해서 사용을 하는데
그 이유는 불필요한 성능저하 방지 및 메모리 효율에 있습니다.(.then을 쓰면 가독성도 챙길수 있음)
프로퍼티는 인스턴스가 생성될 때마다 메모리에 할당되야 하는데 생성된 프로퍼티가 실제로 사용되지 않는 비효율 상황을 대비하여 lazy를 선언합니다.
lazy(지연 저장 프로퍼티)를 선언한 코드는 해당 코드에 직접 접근해서 실행시키기 전까지 인스턴스화 되지 않습니다.
다만 무조건 lazy가 좋은것은 아닙니다. 반드시 수행되어야 하는 경우에는 오히려 연산이 추가되어 독이 될 수 있습니다.
상황에 맞게 사용하는것이 가장 중요합니다.
final class RankingFeatureSectionView: UIView {
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 18.0, weight: .black)
label.text = "iPhone이 처음이라면"
return label
}()
private lazy var showAllAppsButton: UIButton = {
let button = UIButton()
button.setTitle("모두 보기", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 14.0, weight: .semibold)
return button
}()
}
class
나 struct
의 다른 프로퍼티의 값을 lazy
변수에서 사용하기 위해서는 closure
내에서 self
를 통해 접근이 가능합니다.
기본적으로 일반 변수들은 클래스가 생성된 이후에 접근이 가능하기 때문에 클래스내의 다른 영역(메소드, 일반 프로퍼티)에서는 self
를 통해 접근할 수 없지만 lazy
키워드가 붙으면 생성 후 추후에 접근할 것이라는 의미이기 때문에 closure
내에서 self
로 접근이 가능합니다.
아래 예시를 보면 lazy를 더 체감할 수 있습니다.
class SleepingBeauty {
init() {
print("zzz...sleeping...")
sleep(2)
print("sleeping beauty is ready!")
}
}
class Castle {
var princess = SleepingBeauty()
init() {
print("castle is ready!")
}
}
print("a new castle...")
let castle = Castle()
-------------------------------------------------
a new castle...
zzz...sleeping...
sleeping beauty is ready!
castle is ready!
class SleepingBeauty {
init() {
print("zzz...sleeping...")
sleep(2)
print("sleeping beauty is ready!")
}
}
class Castle {
lazy var princess = SleepingBeauty()
init() {
print("castle is ready!")
}
}
print("a new castle...")
let castle = Castle()
castle.princess
-------------------------------------------------
a new castle...
castle is ready!
zzz...sleeping...
sleeping beauty is ready!