iOS / Swift:无法为UILabel文本属性分配可选字符串 [英] iOS/Swift: Can't assign optional String to UILabel text property
问题描述
UILabel有一个text属性,它是一个可选的String,但它看起来像是一个隐式解包的可选项。为什么我不能为它分配另一个可选的字符串?谢谢。
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.
@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
推荐答案
您不需要打开文本
。
离开 text
as String?
(又名可选< String>
)
cell.tweetContent.text = unopt // Works: String implicitly wraps to Optional<String>
cell.tweetContent.text = opt // Works: Optional<String>
展开文本
转为字符串?
到字符串
。
cell.tweetContent.text? = unopt // Works: String
cell.tweetContent.text? = opt // Fails: Optional<String> cannot become String
UPDATE
也许这里需要更多的解释。 text?
比我原先想象的要差,不应该使用。
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 = value
和文字? = value
作为函数 setText
。
text =
具有签名 func setText(value:String?)
。请记住,字符串?
是可选< String>
。此外,无论 text
的当前值如何,它总是被调用。
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)
。这是捕获,只有在 text
有值时才会调用它。
text? =
has the signature func setText(value: String)
. Here is the catch, it's only called when text
has a value.
cell.tweetContent.text = nil
cell.tweetContent.text? = "This value is not set"
assert(cell.tweetContent == nil)
这篇关于iOS / Swift:无法为UILabel文本属性分配可选字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!