简体   繁体   English

的NSString? 不能转换为'StringLiteralConvertible'&?! 在斯威夫特

[英]NSString? is not convertible to 'StringLiteralConvertible' & ?! in Swift

In Class AI have this variable: 在AI类中,具有以下变量:

var collectionElement  : PFObject?

I then need to call a method which users it. 然后,我需要调用一个用户使用的方法。 But before I want to check if it is nil or not. 但是在我想检查它是否为零之前。 So I do something like: 所以我做类似的事情:

if collectionElement != nil{

  if let elementName = collectionElement["elementName"] as? NSString{
    elementTitle.text = elementName as String
  }
       ...

  query.whereKey("fileCollectionElement", equalTo:collectionElement!)
}

In class BI assign the value like this: 在BI类中,如下分配值:

cell.collectionElement = collectionElements[indexPath.row]

where collectionElements[indexPath.row] is a PFObject. 其中collectionElements [indexPath.row]是PFObject。

This code gives me errors, and by playing around with the ! 这段代码给了我错误,并且玩弄了! and ?, I can make the app run but it crashes, specifically because of the line coll... != nil 和?,我可以使应用程序运行,但会崩溃,特别是由于行coll ...!= nil

I am really confused with the ? 我真的很困惑吗? and ! 和! things. 的东西。 What is the right thing to use and when? 什么时候使用正确的东西? Why sometimes I cannot check if something is nil (in Objective-C I could do it all the time)? 为什么有时我不能检查是否为零(在Objective-C中我可以一直做到)?

? and ! 和! for variables: ? 对于变量: is used when the the variable could be an object or can be nil. 当变量可以是对象或可以为nil时使用。 ! is used when the variable could be an object or can be nil BUT it should never be nil. 当变量可能是一个对象或可以为nil时使用,但绝对不能为nil。 This prevents the coder from having to unwrap it everytime. 这样可以避免编码器每次都必须拆开包装。

? and ! 和! for casting: "x as? y" checks if the "x" CAN be casted as "y" AND it if so it WILL be casted as "y". 转换:“ x as?y”检查是否可以将“ x”转换为“ y”,如果可以,则将其转换为“ y”。 "x as! y" forces the cast from x to y “ x as!y”强制将x强制转换为y

So in your code you should check as? 因此,在您的代码中应检查为? String, because it seems like you are trying to cast it later on anyway to String. 字符串,因为您似乎以后无论如何都要尝试将其转换为字符串。 So try this: 所以试试这个:

    if collectionElement != nil{

      if let elementName = collectionElement["elementName"] as? String{
        elementTitle.text = elementName 
      }
           ...

      query.whereKey("fileCollectionElement", equalTo:collectionElement!)
    }

As for the error when you index countElements, this could return a nil value so you should make sure the two sides agree on the type they working with. 至于索引countElements时的错误,这可能会返回nil值,因此您应确保双方在使用它们的类型上达成共识。 if countElements contains an optional (PFObject?) then make sure cell.collection element is an optional (PFObject?) also. 如果countElements包含可选的(PFObject?),请确保cell.collection元素也是可选的(PFObject?)。

Having the same exact types is crucial in Swift. 在Swift中,具有相同的确切类型至关重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM