[Swift] Guard and If

👉🏻 스위트프의 guard문법에 대한 설명입니다.
This is an explanation of the guard syntax in Sweets.

👉🏻 guard대신 if를 사용해도됩니다.
You can use if instead of guard.

👉🏻 gurard를 사용할 경우 코드 읽기가 더 쉬워집니다.
Using gurard makes your code easier to read.

👉🏻 guard는 다음과 같은 구조를 가집니다.
The guard has the following structure:

✔️ guard의 조건과 같으면 통과하고 조건과 다르면 else 블럭을 실행합니다.
If it matches the guard condition, it passes, and if it doesn’t, the else block is executed.

guard 조건 [ condition ] else {
    // 조건이 false일 때 실행되는 부분
    // The part that runs when the condition is false

    // 보통 return, break, continue, throw 등으로 탈출
    // Usually escape with return, break, continue, throw, etc.
}

👉🏻 코드 / Code

✔️ 아래는 guard를 사용하는 앱의 코드 입니다.
Below is the code for an app that uses guard.

✔️ UI에 값을 표시하려면 .onAppear(){} 안에 함수를 실행합니다.
To display a value in the UI, run a function inside .onAppear(){}.


import SwiftUI

struct ContentView: View {
    @State var text:String = ""
    
    func process(_ value: Int?) {
        
        // 해당 조건과 다르면 모두 통과 됩니다.
        // If it is different from the condition, everything passes.
        guard let value = value else { return }
        guard value > 0 else { return }
        guard value != 999 else {  return }

        // 위의 guard를 모두 통과시 다음 부분을 처리 합니다.
        // If all of the guards above are passed, the next part is processed.
        print("Print Value:", value)
        text = "\(value)"
    }
    
    init(){
        
        // 제일 처음실행되며 여기서 함수실행시 ui에 표시되지 않음
        // It is executed first and is not displayed in the UI when the function is executed here.
        
        // process(Int(2));
    }


    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            
            Text("Text1:\(text)")

        }
        .padding()
        .onAppear(){
            
            // ui에 값을 정상적으로 표시하려면 여기에 표시할 것
            // If you want to display the value normally in the ui, display it here
            
            process(Int(2))
        }
    }
}

#Preview {
    ContentView()
}

👉🏻 스크린 샷 / ScreenShot

Leave a Reply