0

So I found this code to query your database while the user is still typing, but the code was outdated and I've been updating it, but there's an error that I don't know how to fix.

func findFriends(text: String) -> Void {

    let ref = Database.database().reference()
    ref.child("users").queryOrdered(byChild: "username").queryStarting(atValue: text).queryEnding(atValue: text+"\u{f8ff}").observe(.value, with: { snapshot in

        let user = User()
        let userArray = [User]()

            for u in snapshot.children{
                user.name = u.value!["name"] as? String
        }
    })

I get an error in the last line and it says:

Value of type 'Any' has no member 'value'

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Seems like the same issue as in [this question](https://stackoverflow.com/q/42026284/4916627) although thats a different swift version. – André Kool Apr 20 '19 at 13:41
  • Possible duplicate of [Type 'Any' has no subscript members (firebase)](https://stackoverflow.com/questions/39136026/type-any-has-no-subscript-members-firebase) – André Kool Apr 20 '19 at 13:42
  • @AndréKool Looks similar, but I'm not to sure how i would implement this with my for loop. – daniel ekhorugue Apr 20 '19 at 13:45

1 Answers1

1

The elements in snapshot.children are of type Any, which doesn't have a value property. To get at the value property you need to cast u to a DataSnapshot:

for userSnapshot in snapshot.children{
    let userSnapshot = userSnapshot as! DataSnapshot
    guard let dictionary = userSnapshot.value as? [String: Any] else { return }
    user.name = dictionary["name"] as? String
}

Alternatively, you put the cast in the loop:

for userSnapshot in in snapshot.children.allObjects as? [DataSnapshot] ?? [] {
    guard let dictionary = userSnapshot.value as? [String: Any] else { return }
    user.name = dictionary["name"] as? String
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807