斯威夫特:关于展开的奇怪行为 [英] Swift: strange behavior about unwrapping
问题描述
在我的Child模型中,我声明了以下属性:
In my Child model, I have declared the following properties:
var name:String?
var year:String?
var make:String?
var model:String?
和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
但如果我想使用它们,我必须解开child.year,child.make,child.model。这是为什么?
cell!.detailTextLabel.text = child.year! + " " + child.make! + " " + child.model!
我跟着这个 tutorial 并成功构建项目。在那个项目中,在类似的情况下,我不需要打开包装。 代码
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
推荐答案
您需要显式解包,因为您使用的是串联运算符。没有为可选字符串定义连接,因此您需要添加感叹号以打开值。如果你使用字符串插值,你应该可以避免它,如下所示:
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.
这篇关于斯威夫特:关于展开的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!