Swift: strange behavior about unwrapping

ぃ、小莉子 提交于 2019-12-24 01:54:44

问题


In my Child model, I have declared the following properties:

var name:String?
var year:String?
var make:String?
var model:String?

and the init:

init(name:String, ... ,year:String, make:String, model:String, ...){
    self.name = name
    ...
    self.year = year
    self.make = make
    self.model = model
}

Here I construct a child:

Child(name:cName,...,year:cYear,make:cMake, model:cModel,...)

In

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ 

For the child's name I could use it directly without unwrapping:

cell!.textLabel.text = child.name

But I have to unwrap child.year, child.make, child.model if I want to use them. Why is that?

cell!.detailTextLabel.text = child.year! + " " + child.make! + " " + child.model!

I followed this tutorial and build the project successfully. In that project, in a similar situation, I don't need to do unwrapping. Code

cell.text = album.title
cell.image = UIImage(named: "Blank52")
cell.detailTextLabel.text = album.price

回答1:


You need an explicit unwrap because you are using concatenation operator. Concatenation is not defined for optional strings, so you need to add exclamation point to unwrap the values. You should be able to avoid it if you use string interpolation, like this:

cell!.detailTextLabel.text = "\(child.year) \(child.make) \(child.model)"

Note: if the initializer that you show is the only one available, you should be able to make your strings non-optional.



来源:https://stackoverflow.com/questions/24844495/swift-strange-behavior-about-unwrapping

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