[Swift] Guard and If

๐Ÿ‘‰๐Ÿป ์Šค์œ„ํŠธํ”„์˜ guard๋ฌธ๋ฒ•์— ๋Œ€ํ•œ ์„ค๋ช…์ž…๋‹ˆ๋‹ค.
This is an explanation of the guard syntax in Swift.

๐Ÿ‘‰๐Ÿป 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