简体   繁体   English

表格视图单元格可选-快速

[英]Table view cell Optional - swift

I have researched this question to no end but continue to struggle. 我一直在研究这个问题,但是一直在努力。 I have seen the following code written as : cell.textLabel?.text when creating cells. 创建单元时,我已经看到以下代码写为:cell.textLabel?.text。 Why is there a question mark only on textLabel and not text? 为什么仅在textLabel上没有问号?

According to apple docs, textLabel is an optional property of type UILabel and text is an optional string, yet we only use one question mark? 根据Apple的文档,textLabel是UILabel类型的可选属性,而text是可选字符串,但是我们仅使用一个问号吗? Why not two questions marks, one for each optional? 为什么不问两个问号,每个问号一个?

The textLabel of UITableViewCell is optional because the label can be missing when using a custom cell. UITableViewCelltextLabel是可选的,因为使用自定义单元格时可能会丢失标签。

If you are using the standard cell with one of the 4 predefined styles textLabel is guaranteed to exist and you can safely unwrap the optional: cell.textLabel!.text 如果您将标准单元格与4种预定义样式之一textLabel则保证textLabel存在,并且可以安全地展开可选的单元格: cell.textLabel!.text

To answer the question the first question mark is required for Optional Chaining , any optional except the last item in a chain ( foo.bar.baz ) must be marked as optional or unwrapped. 要回答这个问题,“ 可选链接”需要第一个问号,除了链中的最后一项( foo.bar.baz )以外,任何可选选项都必须标记为“可选”或未包装。 In case of the last item the compiler can "negotiate" a type match directly with the item across the equal sign. 在最后一项的情况下,编译器可以直接在等号上“协商”与该项的类型匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM