SwiftUI_visionOS_Note

SAFE CODING: if let & guard

Mar 12, 2024
2 min read|

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")
        }

    }
}
swift

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"
        }
    } 
    
}
swift

onAppear will load the data which dispatch the function after 3 seconds.

What if diplayText has an empty value?

@State var displayText: String? = nil
swift
  • Then code won’t be working.
  • we have to say if displayText exist, it runs
               if let text = displayText{
                    Text(text)
                        .font(.title)}
swift

add a loading indicator

  1. Create a boolean

@State var isLoading: Bool = false

  1. add isLoading inside the loadData functino
    func loadData() {
        isLoading = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 3){
            displayText = "This is the new data"
        }
        isLoading = false
    }
swift

on Appear, is loading will be true, after three seconds, it runs the code and change the loading boolean to false

  1. While it’s loading, we show progressView()
if isLoading{
	ProgressView()
}
swift

Simulate the user data in the app

  1. Create a nil variable of currentUserID

@State var currentUserID: String? = nil

Lets make loadData works when they have an user ID

    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"
        }
        
        

    }
swift

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
 
    }
    
swift
  • 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.

Subscribe to our newsletter

Get the latest news and updates from our team