Swift string vs. string! vs. string?

后端 未结 4 1833
眼角桃花
眼角桃花 2021-01-06 09:03

I have read this question and some other questions. But they are somewhat unrelated to my question

For UILabel if you don\'t specify

4条回答
  •  旧时难觅i
    2021-01-06 09:37

    All this is covered in the documentation: The Swift Programming Language - The Basics.

    In short:

    String represents a String that's guaranteed to be present. There is no way this value can be nil, thus it's safe to use directly.

    String? represents a Optional, which can be nil. You can't use it directly, you must first unwrap it (using a guard, if let, or the force unwrap operator !) to produce a String. As long as you don't force unwrap it with !, this too is safe.

    String! also represents an Optional, which can be nil. However, this optional can be used where non-optionals are expected, which causes implicit forced unwrapping. It's like having a String? and having it always be implicitly force unwrapped with !. These are dangerous, as an occurrence of nil will crash your program (unless you check for nil manually).

提交回复
热议问题