在 A 类中我有这个变量:
var collectionElement : PFObject?
然后我需要调用一个使用它的方法。但在我想检查它是否为零之前。所以我做了类似的事情:
if collectionElement != nil{
if let elementName = collectionElement["elementName"] as? NSString{
elementTitle.text = elementName as String
}
...
query.whereKey("fileCollectionElement", equalTo:collectionElement!)
}
在 B 类中,我这样分配值:
cell.collectionElement = collectionElements[indexPath.row]
其中 collectionElements[indexPath.row] 是一个 PFObject。
这段代码给我错误,并且通过玩弄 !和?,我可以让应用程序运行但它崩溃了,特别是因为行 coll... != nil
我真的很困惑?和 !事物。什么是正确的使用时间?为什么有时我无法检查某些东西是否为 nil(在 Objective-C 中我可以一直这样做)?
最佳答案
?和 !对于变量: ?当变量可以是对象或可以是 nil 时使用。 !当变量可以是一个对象或者可以是 nil 但它永远不应该是 nil 时使用。这可以防止编码器每次都必须打开它。
?和 !用于类型转换: “x as?y”检查“x”是否可以转换为“y”,如果可以,它将转换为“y”。 "x as!y"强制转换从 x 到 y
所以在您的代码中您应该检查为?字符串,因为看起来您稍后试图将它强制转换为字符串。所以试试这个:
if collectionElement != nil{
if let elementName = collectionElement["elementName"] as? String{
elementTitle.text = elementName
}
...
query.whereKey("fileCollectionElement", equalTo:collectionElement!)
}
至于索引 countElements 时的错误,这可能会返回一个 nil 值,因此您应该确保双方就他们使用的类型达成一致。如果 countElements 包含一个可选的(PFObject?),那么确保 cell.collection 元素也是一个可选的(PFObject?)。
拥有完全相同的类型在 Swift 中至关重要。
关于ios - 字符串?不能转换为 'StringLiteralConvertible' & ?!在 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882170/