23.12.14 TIL SwiftUI 12. How to use inits and enums

Hay·2023년 12월 14일
0

SwiftUI_Beginner

목록 보기
8/19

How to use inits and enums

  • 이니셜라이져를 통해 매번 같은 것을 입력하지 않도록 효율적으로 코딩
  • 이넘을 이용해서 마찬가지로 더 간단하고 효율적으로 코딩할 수 있다
import SwiftUI

struct InitializerBootcamp: View {
    //body 밖에 데이터를 storing 할 수 있다. 그리고 이걸 body 안에서 사용할 수 있다.
    
    //이런식으로 변수로 만들어서 사용하면 나중에 수정하기 편하다.
    let backgroundColor: Color
    let count: Int
    let title: String
    
    init(count: Int, fruit: Fruit) { //아래에 작성한 enum 사용하기
        self.count = count //self.count -> 위의 let count의 count이고, 등호 오른쪽의 count는 init()안의 count이다.
        
        if fruit == .apple {
            self.title = "Apples"
            self.backgroundColor = .red
        } else {
            self.title = "Oranges"
            self.backgroundColor = .orange
        }
        
        //enum을 쓸거라서 이제 아래의 코드는 필요없어졌다.
//        self.title = title
//        
//        if title == "Apples" { //이렇게 title에 따라서 backgroundColor를 변경하도록 코드를 짤 수 있다.
//            self.backgroundColor = .red
//        } else {
//            self.backgroundColor = .orange
//        }
    }
    
    enum Fruit {
        case apple
        case orange
    }
    
    var body: some View {
        VStack(spacing: 12) {
            Text("\(count)")
                .font(.largeTitle)
                .foregroundColor(.white)
                .underline()
            
            Text("\(title)")
                .font(.headline)
                .foregroundColor(.white)
        }
        .frame(width: 150, height: 150)
        .background(backgroundColor)
        .cornerRadius(10)
    }
}

#Preview {
    HStack {
        InitializerBootcamp(count: 100, fruit: .apple)
        InitializerBootcamp(count: 46, fruit: .orange)
    }
    
}

0개의 댓글