SwiftUI_visionOS_Note

SAFE CODING: if let & guard

Mar 12, 2024

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.

 
Callout icon'
THE MOST IMPORTANT VIDEO
 
 

Create a NavStack

 

Add a loadData function

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

 

What if diplayText has an empty value?

  • Then code won’t be working.
  • we have to say if displayText exist, it runs
 
 

add a loading indicator

  1. Create a boolean

@State var isLoading: Bool = false

 
  1. add isLoading inside the loadData functino

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()
 
 

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

 
 

Use Guard to make the code safer

  • 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

Callout icon'
by adding ! at the end will force the code, but it will break the entire app.
 
 
 

You might also like

BlogPro logo
Made with BlogPro