Lazy - siwonkim0/ios-project-manager GitHub Wiki

Lazy ν‚€μ›Œλ“œ μ‚¬μš©μ— λŒ€ν•œ κ³ λ―Ό

private lazy var entireStackView: UIStackView = {
        let stackView = UIStackView(arrangedSubviews: [titleLabel, totalCountLabel, spacerView])
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.distribution = .fill
        stackView.spacing = Design.entireStackViewSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()

Lazy ν‚€μ›Œλ“œμ˜ μ‚¬μš© μš©λ„λŠ” μ²˜μŒλΆ€ν„° λ©”λͺ¨λ¦¬μ— μ˜¬λ¦¬μ§€ μ•Šκ³ , ν˜ΈμΆœμ‹œ λ©”λͺ¨λ¦¬μ— 올리기 μœ„ν•΄ μ‚¬μš©ν•˜λŠ” 것이닀.

Lazy ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©μ‹œ μ£Όμ˜ν•  점에 λŒ€ν•΄μ„œ κ³ λ―Όν•΄λ³΄μ•˜λ‹€.

λ©”λͺ¨λ¦¬ λˆ„μˆ˜

첫번째둜 λ³€μˆ˜μ— ν΄λ‘œμ €μ˜ μ‹€ν–‰ κ²°κ³Όλ₯Ό ν• λ‹Ήν•˜λŠ” κ²½μš°λŠ” λ©”λͺ¨λ¦¬ λˆ„μˆ˜μ˜ μœ„ν—˜μ΄ μ—†λ‹€.

λ‘λ²ˆμ§Έλ‘œ λ³€μˆ˜μ˜ νƒ€μž…μ„ ν΄λ‘œμ €λ‘œ μ„€μ •ν•˜μ—¬ ν΄λ‘œμ € μ‹€ν–‰μ˜ κ²°κ³Όκ°€ μ•„λ‹Œ ν΄λ‘œμ € 자체λ₯Ό λ‹΄κ³  μžˆλŠ” λ³€μˆ˜λΌλ©΄ λ©”λͺ¨λ¦¬ λˆ„μˆ˜μ˜ μœ„ν—˜μ„±μ΄ μžˆμ–΄μ„œ [weak self]둜 λ©”λͺ¨λ¦¬ λˆ„μˆ˜λ₯Ό λ°©μ§€ν•΄μ€˜μ•Όν•œλ‹€.

lazy var greeting: String = {
    return "Hello my name is \((self.name))"
}()
lazy var greeting: () -> String = { [weak self] in
    return "Hello my name is \(((self?.name))!)"
}

μ‚¬μš©μ‹œ μ£Όμ˜ν•  점은 만일 ν•΄λ‹Ή ν΄λ‘œμ €μ—μ„œ selfλ₯Ό μ°Έμ‘°ν•  μ‹œ λ©”λͺ¨λ¦¬ λˆ„μˆ˜κ°€ λ°œμƒν•  수 μžˆλ‹€λŠ” 점이 μžˆλ‹€.

λ˜ν•œ swift μ½”λ“œλŠ” 기본적으둜 thread-safe ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— μ—¬λŸ¬ μŠ€λ ˆλ“œκ°€ λ™μ‹œμ— ν•΄λ‹Ή lazy var λ³€μˆ˜μ— μ ‘κ·Όν•œλ‹€λ©΄ ν•΄λ‹Ή lazy λ³€μˆ˜κ°€ μ—¬λŸ¬λ²ˆ 생성될 μœ„ν—˜μ΄ μžˆμœΌλ―€λ‘œ lazy var λŠ” λ©€ν‹° μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ μ ‘κ·Όν•˜λ©΄ μ•ˆλœλ‹€.

μœ„ 사항듀에 λŒ€ν•΄ κ³ λ―Όν•΄λ³Έ κ²°κ³Ό ν•΄λ‹Ή μ½”λ“œλŠ” λ©”λͺ¨λ¦¬ λˆ„μˆ˜λ  일이 μ—†μŒμ„ ν™•μΈν•˜μ˜€κ³ , lazy의 μš©λ„μ™€ 달리 stackViewλŠ” μ²˜μŒλΆ€ν„° λ©”λͺ¨λ¦¬μ— μ˜¬λ €μ•Όλ˜λŠ” λ·°μ΄λ―€λ‘œ μ“Έ ν•„μš”κ°€ 없어보여 μ œκ±°ν•˜μ˜€μŒ

private let entireStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.distribution = .fill
        stackView.spacing = Design.entireStackViewSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()