In Swift, variables can be declared as optional using the '?' symbol, indicating they may be nil. To safely check and unwrap these optional variables, 'if let' and 'guard' statements are recommended. These methods are safer than explicitly unwrapping optionals using the '!' symbol, which should be avoided.
✅
THE MOST IMPORTANT VIDEO
Create a NavStack
struct ContentView: View {
@State var displayText: String = ""
var body: some View {
NavigationStack{
VStack{
Text("Here we are practicing safe coind!")
Text(displayText)
Spacer()
}
.navigationTitle("Title")
}
}
}
Add a loadData function
struct ContentView: View {
@State var displayText: String = ""
var body: some View {
NavigationStack{
VStack{
Text("Here we are practicing safe coind!")
Text(displayText)
Spacer()
}
.navigationTitle("Title")
.onAppear{
loadData()
}
}
}
func loadData() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3){
displayText = "This is the new data"
}
}
}
onAppear will load the data which dispatch the function after 3 seconds.
What if diplayText has an empty value?
@State var displayText: String? = nil
- Then code won’t be working.
- we have to say if displayText exist, it runs
if let text = displayText{
Text(text)
.font(.title)}
add a loading indicator
- Create a boolean
@State var isLoading: Bool = false
- add isLoading inside the loadData functino
func loadData() {
isLoading = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3){
displayText = "This is the new data"
}
isLoading = false
}
on Appear, is loading will be true, after three seconds, it runs the code and change the loading boolean to false
- While it’s loading, we show progressView()
if isLoading{
ProgressView()
}
Simulate the user data in the app
- Create a nil variable of currentUserID
@State var currentUserID: String? = nil
func loadData() {
if let userID = currentUserID{
isLoading = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3){
displayText = "This is the new data \(userID)"
}
isLoading = false
} else{
displayText = "Sign in to continue"
}
}
Use Guard to make the code safer
func loadData2() {
guard let userID = currentUserID else {
displayText = "Sign in to continue"
return
}
isLoading = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3){
displayText = "This is the new data \(userID)"
}
isLoading = false
}
- if currentUserID isn’t userID, it shows sign in text and stop the function by return. if there is a value, than run the rest of the code below.
Force the code
✅
by adding ! at the end will force the code, but it will break the entire app.