23.12.21 TIL SwiftUI 22. How to use Ternary Operators

Hay·2023년 12월 21일
0

SwiftUI_Beginner

목록 보기
18/19

How to use Ternary Operators

if-else 대신에 Ternary Statement를 사용하면 훨씬 더 간략하고 깔끔하게 코드를 짤 수 있다

import SwiftUI

struct TernaryBootcamp: View {
    
    @State var isStartingState: Bool = false
    
    var body: some View {
        VStack {
            Button("Button: \(isStartingState.description)") {
                isStartingState.toggle()
                
            }
            
            
            Text(isStartingState ? "STARTING STATE!" : "ENDING STATE.")
            
            //Ternary Statement 사용예시 2
            //모든 코드에 Ternary Statement를 적용해봄
            RoundedRectangle(cornerRadius: isStartingState ? 25 : 0)
                .fill(isStartingState ? Color.red : Color.blue)
                .frame(
                    width: isStartingState ? 200 : 50,
                    height: isStartingState ? 400 : 50)
            
            
            //-----------------------------------------------------
            //Ternary Statement 사용예시 1
            RoundedRectangle(cornerRadius: 25.0)
                .fill(isStartingState ? Color.red : Color.blue)
                //-> 여기에 Ternary Statement를 사용. if-else랑 동일한 기능을 한다.
                // isStartingState == true 라면, Color.red를 실행
                // 아니라면 Color.blue. 훨씬 간단하게 코딩할 수 있다.
                .frame(width: 200, height: 100)
            
            
            
            //-----------------------------------------------------
            //if문을 사용하여 색을 바꾸는 방법
            //이렇게 if를 사용할 수도 있지만 이렇게 코딩하게 되면,
            //사각형의 색이 변경되는 것이 아니라 아예 새로운 사각형을 만드는 것이다
            //또 if 와 else의 코드가 색을 제외하고는 동일한 코드이다.
            // -> 따라서 이런 상황에서는 Ternary Operator를 사용하는 것이 더 낫다.
            if isStartingState {
                RoundedRectangle(cornerRadius: 25.0)
                    .fill(Color.red)
                    .frame(width: 200, height: 100)
            } else {
                RoundedRectangle(cornerRadius: 25.0)
                    .fill(Color.blue)
                    .frame(width: 200, height: 100)
            }
 
            Spacer()
        }
    }
}

#Preview {
    TernaryBootcamp()
}


0개의 댓글