SwiftUI/SwiftUI(Basic)

11. [SwiftUI] init()

Toughie 2023. 4. 12. 23:33

SwiftUI에서는 Structure를 주로 사용하다 보니, 생성자에 대한 고려를 크게 하지 않고 있었다.

구조체에서는 memberwise initializer가 자동으로 제공되기 때문이다.

 

그런데 재사용성을 고려하고, 효율적인 코딩을 위해서는 생성자의 개념이 필요한 순간이 있을 수 있다.

ex. 거의 같은 뷰인데 속성만 조금씩 바뀌는 경우

 

열거형과 생성자를 이용해 좀 더 효율적으로 비슷한 뷰를 그리는 방식에 대해 알아보자.

//
//  Created by Toughie on 2023/04/12.
//

import SwiftUI

struct initializer: View {

	//프로퍼티에 타입만 지정
    let backgroundColor: Color
    let count: Int
    let title: String
    
    enum Animal {
        case dog
        case cat
    }
    // 생성자를 통해 초기화. count는 인자 argument로 직접 받고, title과 backgroundColor는 조건문으로 처리
    init(count: Int, animal: Animal) {
        self.count = count
        
        if animal == .dog {
            self.title = "Dogs"
            self.backgroundColor = .blue
        } else {
            self.title = "Cats"
            self.backgroundColor = .yellow
        }
    }
    
    var body: some View {
        VStack(spacing: 15) {
            Text("\(count)")
                .font(.largeTitle)
                .foregroundColor(.white)
                .underline()
            Text(title)
                .font(.headline)
                .foregroundColor(.white)
        }
        .frame(width: 150, height: 150)
        .background(backgroundColor)
        .cornerRadius(15)

    }
}

struct initializer_Previews: PreviewProvider {
    static var previews: some View {
        HStack {
            initializer(count: 17, animal: .dog)
            initializer(count: 20, animal: .cat)
        }
    }
}

 

구조체의 특성상 꼭 생성자를 따로 구현해줄 필요는 없지만,

위의 예시와 같이 값을 할당하지 않고 타입만 지정한 후 생성자를 통해 인스턴스를 찍어내면

비슷한 뷰들을 효율적으로 찍어낼 수 있는 장점이 있다.

 

이를 위해 이어서 forEach 를 알아보도록 하자.