Swift string vs. string! vs. string?

后端 未结 4 1802
眼角桃花
眼角桃花 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条回答
  •  一生所求
    2021-01-06 09:55

    The whole "optional" thing messed with me bad at first. What made it "click" for me, was when I stopped thinking of those as "String" objects and started thinking of them as generics. Just like "Array" with generic identifier for "String" is an array that, if it has values, contains strings... "String?" is an Optional that, if it has a value, is a string.

    String - This is always guaranteed to be some kind of string, and NEVER nil. When you declare a variable, it must be given a value.

    String? - This is an optional. It can be nil, and IF it has a value, it will be a string. In order to access the optional's value, you must unwrap it.

    String! - This is an optional, with syntax sugar that lets you access its value directly as if it where just a String. It COULD be nil, but for whatever reason, the context around the variable has winked at you and said "don't worry, it will have a value."

提交回复
热议问题