can not convert value type “string?” to expected argument type “inout string”

只谈情不闲聊 提交于 2020-01-12 07:26:59

问题


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

can not convert value type "string?" to expected argument type "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 is the inout string here ? what is the best practice ?

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


回答1:


You need to write it like this instead:

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

It´s because of the left side is an optional and the right side is not and they don´t match. That´s why you need to write label.text = label.text +...

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

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



回答2:


I suggest you use the optional chaining operator to only perform the addition of text if the optional (self.displayResultLable.text) is non-nil:

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


来源:https://stackoverflow.com/questions/39974931/can-not-convert-value-type-string-to-expected-argument-type-inout-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!