Don’t Let This Simple Swift Function Crash Your Firebase App
If you’ve worked with Firebase in SwiftUI, you’ve probably come across a common pattern that looks like this:
func getUserId() -> String {
guard let uid = Auth.auth().currentUser?.uid else {
return ""
}
return uid
}It looks harmless, right? A simple utility function to fetch the current authenticated user’s UID. Yet, this exact snippet led to a fatal crash in a production SwiftUI app. Let’s walk through what went wrong, why it happened, and how to avoid such pitfalls in future projects.
The Error :
The app crashed at runtime with the following error:
Thread 1: "Invalid path (users//expense). Paths must not contain // in them."This happened while trying to read data from Firestore using a path like:
Firestore.firestore().collection("users/{uid}/expense")This essentially became:
Firestore.firestore().collection("users//expense")Notice the double slashes //. That empty string in the middle? That came from getUserId() returning "".
Understanding the Root Cause :
The core of the issue lies in when and how this getUserId() function is called.
Auth.auth().currentUser is nil on launch :
When your SwiftUI app launches, FirebaseAuth may not have completed the process of rehydrating the authenticated user session. If you call Auth.auth().currentUser?.uid too early, especially in initial view initializers or @StateObjectconstructors, you may end up with nil.
Get Purushothaman Manikumar’s stories in your inbox
Join Medium for free to get updates from this writer.
The guard statement in getUserId() silently returns "", which propagates and creates invalid Firestore paths like users//expense.
How to Avoid this ?
Instead of returning an empty string if the current user ID is null, we can return the current user ID as an optional.
func getUserId() -> String? {
Auth.auth().currentUser?.uid
}And this is how it should be handled safely
if let uid = getUserId() {
Firestore.firestore().collection("users/{uid}/expense")
} else {
// Loading view ...
}In Conclusion :
This bug is a textbook example of how asynchronous state in SwiftUI and silent fallback logic can cause unpredictable runtime errors. A single empty string returned too early became a double-slash path that crashed the app.
The main takeaways:
- Never assume
Auth.auth().currentUseris immediately available.
2. Avoid returning placeholder values like "" that silently propagate errors.
3. Handle asynchronous auth state reactively with listeners or stateful objects.
Thanks for reading! I hope this helps you avoid similar issues in your SwiftUI + Firebase journey. If you have any questions or want a sample project using the safe pattern, let me know in the comments.





