展开可选值

时间:2015-03-06 22:50:51

标签: swift optional

我正在尝试解析其中包含这些值的可选值

Optional(UITableViewCell: ox7ff2f9cfbc80; frame = (0 0; 414 44); text = 'Clarity'; autoresize = W; layer = <CALayer:0x7ff2f9cfb250>>)

并希望抓住“Clarity&#39;”的文本部分。打印出另一行。如果这是可能的,请告诉我,因为我是Swift的新手!谢谢!

以下是我如何创建表格单元格

我有一个歌曲列表

tracks = [Clarity, Freak-a-Leek, What's My Age Again?, All The Small Things, Bandz A Make Her Dance, Cant Tell Me Nothing, Slow Jamz, Hate It Or Love It, Dark Horse, Teenage Dream, In Too Deep, Just Hold On, We're Going Home, Energy, Fat Lip]

并通过执行以下操作创建tableviewcells

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell

    cell?.textLabel?.text=self.tracks[indexPath.row]
    return cell!
}

以下是我获取可选值的方法

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    println("You selected cell #\(indexPath.row)!")
   let Cell = tableView.cellForRowAtIndexPath(indexPath)

}

1 个答案:

答案 0 :(得分:3)

您可以使用可选链接到达可选项以获取特定字段,然后检查链是否具有if let的值:

if let txt = optionalCell?.text {
    println(txt)
}
// if you want to, add an else
else {
    // to handle the optional chain being nil
}

optionalCell?.text表示:如果optionalCell有值,请获取text属性,否则返回nil。然后,if let“展开”可选项,如果可选项包含一个,则将txt设置为常规值。如果您希望代码处理不存在,则可以添加else子句。

如果你想在nil(例如,一个空字符串)的情况下使用默认值,那么有一个简写:

let txt = optionalCell?.text ?? "Blank"

??在左侧采用可选值,在右侧采用默认值,并计算为可选中的值,如果是nil则为默认值。

您可能会看到人们建议有时使用!不遵循他们的建议!是一个“强制解包”,如果你打开的可选项是nil,你的程序将退出一个断言。 !有合法用途,但它们非常罕见,更常见的是当有更好的解决方案时人们误推荐它

相关问题