Roggie
Roggie

Reputation: 1217

Swift guard let error: Initializer for conditional binding must have Optional type, not '[String : String]' in swift?

I am getting the following error at the line of code below. My app crashes when the value is nil/empty, hence why I am trying to guard unwrap.

Error: Initializer for conditional binding must have Optional type, not '[String : String]'

guard let savedByUsers = venue.childSnapshot(forPath: "bookmarkedByUsers").value as! [String : String] else { return }

Upvotes: 1

Views: 1372

Answers (1)

morenoadan22
morenoadan22

Reputation: 234

change to:

guard let savedByUsers: [String: String] = venue.childSnapshot(forPath: "bookmarkedByUsers").value as? [String: String] else {
    return
}

The as! forces the unwrap and causes an exception when the value is nil. Using as? will avoid that and jump into the else clause.

Upvotes: 2

Related Questions