gk103 gk103 - 1 year ago 104
Swift Question

iterating an array to extract a value from firebase database in swift

might sound like a basic question--but I'm not seeing where I am going wrong..

I end up with either of these two scenarios:

  1. I keep getting the error "Could not cast value of type __NSCFNumber to NSSTring". if I use
    extractedSku = skuList[i]!.value["sku"] as! String

  2. If I remove
    as! String
    it saves it, but it isn't saved as a string. How do I get this to be saved as a string?

I have appended data from firebase into an array

skuArray = [AnyObject?]()

in viewDidLoad, I am iterating skuArray to extract the 'sku' and store into a variable.

var skuArray = [AnyObject?]()
var productDetailArray = [AnyObject?]()

data stored in Sku Array is:

[Optional(Snap (aRandomKey) {
active = 1;
sku = 888888;


let skuList = self.skuArray

for var i = 0; i < skuList.count ; ++i{
let extractedSku = skuList[i]!.value["sku"] as! String

// go into database and extract "products" details by sku
self.databaseRef.child("products/\(extractedSku)").observeEventType(.ChildAdded, withBlock: { (snapshot:FIRDataSnapshot) in


Answer Source

Since the underlying type is NSNumber, use the stringValue property to get a String:

if let extractedSku = (skuList[i]?.value["sku"] as? NSNumber)?.stringValue {
    // use extractedSku which is of type String
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download