迭代数组以从swift中的firebase数据库中提取值

时间:2022-10-16 21:25:34

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

    我一直收到错误“无法将类型__NSCFNumber的值转换为NSSTring”。如果我使用extractSku = skuList [i]!。value [“sku”]为!串

  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

我已将firebase中的数据附加到数组中

skuArray = [AnyObject?]()

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

在viewDidLoad中,我正在迭代skuArray以提取'sku'并存储到变量中。

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

data stored in Sku Array is:

存储在Sku Array中的数据是:

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

viewDidLoad:

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 个解决方案

#1


2  

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

由于底层类型是NSNumber,因此使用stringValue属性来获取String:

if let extractedSku = (skuList[i]?.value["sku"] as? NSNumber)?.stringValue {
    // use extractedSku which is of type String
}

#1


2  

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

由于底层类型是NSNumber,因此使用stringValue属性来获取String:

if let extractedSku = (skuList[i]?.value["sku"] as? NSNumber)?.stringValue {
    // use extractedSku which is of type String
}