xcode iOS/Swift:无法将可选字符串分配给 UILabel 文本属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28608649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS/Swift: Can't assign optional String to UILabel text property
提问by DenverCoder9
UILabel has a text property, which is an optional String, but it seems to be behaving like an implicitly unwrapped optional. Why can't I assign it another optional String? Thanks.
UILabel 有一个 text 属性,它是一个可选的字符串,但它似乎表现得像一个隐式展开的可选。为什么我不能为它分配另一个可选字符串?谢谢。
@IBOutlet weak var tweetContent: UILabel!
...
...
var unopt: String = "foo"
var opt: String? = "bar"
var opt2: String?
opt2 = opt //Works fine
cell.tweetContent.text? = unopt //Works fine
cell.tweetContent.text? = opt //Compile error: Value of optional type 'String?' not unwrapped
回答by Jeffery Thomas
You don't need to unwrap text.
你不需要解开text。
Leaving textas an String?(aka Optional<String>)
text作为String?(又名Optional<String>)离开
cell.tweetContent.text = unopt // Works: String implicitly wraps to Optional<String>
cell.tweetContent.text = opt // Works: Optional<String>
Where as unwrapping textturns String?into a String.
凡为展开text轮番String?成String。
cell.tweetContent.text? = unopt // Works: String
cell.tweetContent.text? = opt // Fails: Optional<String> cannot become String
UPDATE
更新
Maybe there needs to be a bit more of an explanation here. text?is worse than I originally thought and should not be used.
也许这里需要更多的解释。text?比我原先想象的要糟糕,不应该使用。
Think of text = valueand text? = valueas function setText.
将text = value和text? = value视为功能setText。
text =has the signature func setText(value: String?). Remember, String?is Optional<String>. In addition, it's always called no matter the current value of text.
text =有签名func setText(value: String?)。记住,String?是Optional<String>。此外,无论 的当前值如何,它总是被调用text。
text? =has the signature func setText(value: String). Here is the catch, it's only called when texthas a value.
text? =有签名func setText(value: String)。这是捕获,它仅在text具有值时调用。
cell.tweetContent.text = nil
cell.tweetContent.text? = "This value is not set"
assert(cell.tweetContent == nil)

