iOS/Swift:无法为UILabel文本属性分配可选字符串

Den*_*er9 2 xcode optional uilabel ios swift

UILabel有一个text属性,它是一个可选的String,但它看起来像是一个隐式解包的可选项.为什么我不能为它分配另一个可选字符串?谢谢.

@IBOutlet weak var tweetContent: UILabel!
Run Code Online (Sandbox Code Playgroud)

...

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
Run Code Online (Sandbox Code Playgroud)

Jef*_*mas 5

你不需要打开包装text.

留下text作为String?(又名Optional<String>)

cell.tweetContent.text = unopt // Works: String implicitly wraps to Optional<String>
cell.tweetContent.text = opt   // Works: Optional<String>
Run Code Online (Sandbox Code Playgroud)

解缠在哪里text变成String?了一个String.

cell.tweetContent.text? = unopt // Works: String
cell.tweetContent.text? = opt   // Fails: Optional<String> cannot become String
Run Code Online (Sandbox Code Playgroud)

UPDATE

也许这里需要更多的解释.text?比我原先想象的更糟糕,不应该使用.

想想text = valuetext? = value作为功​​能setText.

text =有签名func setText(value: String?).记住,String?Optional<String>.此外,无论当前的价值如何,它总是被称为text.

text? =有签名func setText(value: String).这是捕获,它只在text有值时才被调用.

cell.tweetContent.text = nil
cell.tweetContent.text? = "This value is not set"
assert(cell.tweetContent == nil)
Run Code Online (Sandbox Code Playgroud)