简体   繁体   中英

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

In Class AI have this variable:

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:

cell.collectionElement = collectionElements[indexPath.row]

where collectionElements[indexPath.row] is a 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

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)?

? and ! for variables: ? is used when the the variable could be an object or can be nil. ! is used when the variable could be an object or can be nil BUT it should never be 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" forces the cast from x to 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. if countElements contains an optional (PFObject?) then make sure cell.collection element is an optional (PFObject?) also.

Having the same exact types is crucial in Swift.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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