Swift 比较非可选值会导致错误
我要比较非可选值和nil。但我不能这么做,因为Xcode说: 将“Int”类型的非可选值与nil进行比较总是返回false 所以我创建了Struct,然后创建了变量:Swift 比较非可选值会导致错误,swift,firebase,Swift,Firebase,我要比较非可选值和nil。但我不能这么做,因为Xcode说: 将“Int”类型的非可选值与nil进行比较总是返回false 所以我创建了Struct,然后创建了变量:var-products:[Product]=[] 我如何能将其与零进行比较 if products[indexPath.row].snusPortions == nil { cell.snusPortionsAmountLabel.text = "N/A" }else
var-products:[Product]=[]
我如何能将其与零进行比较
if products[indexPath.row].snusPortions == nil
{
cell.snusPortionsAmountLabel.text = "N/A"
}else
{
cell.snusPortionsAmountLabel.text = String(products[indexPath.row].snusPortions)
}
我给它们赋值如下:
let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
let enumerator = snapshot.children
while let thisProduct = enumerator.nextObject() as? FIRDataSnapshot
{
print(thisProduct.value) // So I may see what the data is like and know how to extract it
// Chances are you'd have to create a dictionary
let thisProductDict = thisProduct.value as! [String:AnyObject]
let productName = thisProductDict["Products"] as! String
let snusPortions = thisProductDict["PortionsCan"] as? Int
let productObject = Product(snusProductTitle: productName, snusNicotine: snusNicotine, snusPortions: snusPortions!, snusFlavor: snusFlavor, snusWeight: snusWeight!, snusShippingWeight: snusShippingWeight, snusProductImageURL: productURL)
self.products.append(productObject)
print(self.products)
}
self.tableView.reloadData()
}
})
这是产品结构:
struct Product {
var snusProductTitle: String
init()
{
snusProductTitle = ""
}
init(snusProductTitle: String){
self.snusProductTitle = snusProductTitle
}
}
测试时,它说
snosportions
是nil
,但我说如果它是nil,就把它设为“N/A”,为什么呢?听起来好像你把自己搞糊涂了,搞不清局部变量snosportions
和产品属性snosportions
在产品定义中,属性snosportions
是一个Int。它永远不能是nil
。因此,在本规范中:
if products[indexPath.row].snusPortions == nil
。。。本产品的snosportions
永远不会为nil
,我们也永远不会将文本设置为“不适用”
现在让我们看看您的其他代码:
let snusPortions = thisProductDict["PortionsCan"] as? Int
这是一个完全不同的
snosportions
。它可以是nil
,也就是说,如果thisProductDict
缺少“PortionsCan”
键,或者它的值不能强制转换为Int。请显示产品的定义。因此,产品的snSportions
是Int。它永远不能是nil
。我知道Firebase数据库中不存在此值。但如果它没有。那么我如何在标签上说它是“不适用”呢?见下面我的答案。您正在显示两段不相关的代码。我希望您不介意-我回滚了您上次的编辑,以便我的答案与您的问题相关。