1

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;
})]

viewDidLoad:

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

    self.productDetailArray.append(snapshot)
})

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks you @vacawama for your help and advise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.