Cannot convert value of type "string?" to the expected type of the argument "inout string"

this line self.displayResultLable.text += (title as! String) throwing error

cannot convert value of type "string?" to the expected type of the argument "inout string"

Here is my code:

  if results.count > 0 { var displayResult : String? for books in results as! [NSManagedObject] { if let title = books.valueForKey("title") { self.displayResultLable.text += (title as! String) } } } 

what does the inout string represent here? What is the best practice?

Note that this line self.displayResultLable.text = (title as! String) works fine:

+8
source share
2 answers

You need to write it as follows:

 self.displayResultLable.text = self.displayResultLable.text! + title as! String 

This is because of the left side is optional, but the right side is not, and they do not match. That is why you need to write label.text = label.text + ...

I can also suggest you change if let to this instead:

 if let title = books.valueForKey("title") as? String { self.displayResultLable.text = (self.displayResultLable.text ?? "") + title } 
+21
source

I suggest you use the optional chaining operator to add text only if the optional ( self.displayResultLable.text ) is not zero:

 self.displayResultLable.text? += (title as! String) 
+1
source

Source: https://habr.com/ru/post/1258016/


All Articles