๐๐ป ์ค์ํธํ์ 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