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
You don't need to unwrap text.
Leaving text as an String? (aka Optional<String>)
cell.tweetContent.text = unopt // Works: String implicitly wraps to Optional<String>
cell.tweetContent.text = opt // Works: Optional<String>
Where as unwrapping text turns String? into a 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.
Think of text = value and text? = value as function 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? = 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)
来源:https://stackoverflow.com/questions/28608649/ios-swift-cant-assign-optional-string-to-uilabel-text-property