问题
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