0
votes

Good evening!

I am attempting to retrieve a Boolean value from firebase in my swift iOS app, but I have run into a silly issue. Unpacking strings from my snapshots is working great, but Bools are another story... I am clearly missing something (hopfully) simple. Here is the code:

for child in snapshot.children{

    let key = (child as AnyObject).key as String
    let shouldBeBool = (child as AnyObject).value as Bool
    ...
    // Do Stuff with the values
}

I am getting a "Type of expression is ambiguous without more context" error on the Let shouldBeBool line.

The code will compile if I change the "as Bool" to "as String", but the app crashes as expected once it attempts to read the Boolean value in the snapshot as a string.

I have also tried this and get the same error:

for child in snapshot.children{

    let key = (child as AnyObject).key as String
    var shouldBeBool: Bool
    shouldBeBool = (child as AnyObject).value as! Bool
    ...
    // Do Stuff with the values
}

I do not understand how force unwrapping it as a Boolean is ambiguous. Does swift have different types of Boolean?

Hopefully I am just missing something silly.

Thank you for your time.

UPDATE The accepted answer worked (Thank you!), with one additional modification. Working code below.

for child in snapshot.children{

    let key = (child as AnyObject).key as String
    let b = (child as! DataSnapshot).value as! NSNumber // Note the double force unwrapping... bad practice?
    let shouldBeBool = Bool(truncating: b)
    ...
    // Do Stuff with shouldBeBool as a boolean and key as a string
}
1

1 Answers

1
votes

According to the documentation of value, one of the concrete types returned is NSNumber and there's a note that it includes booleans, so you need to cast shouldBeBool to NSNumber then use Bool's init(truncating:) to convert the NSNumber to a Bool.

let number = (child as AnyObject).value as NSNumber
let shouldBeBool = Bool(truncating: number) // false if 0, true otherwise