Swift string vs. string! vs. string?

后端 未结 4 1848
眼角桃花
眼角桃花 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:47

    Thanks to Andrew Madsen's answer and all other answers, I learnt a bit myself:

    struct pairOfOptionalAndNonOptionalAndImplicitUnwrapped{
        var word1 :String?
        var word2 :String
        var word3: String!
    
        init (a:String, b: String, c: String){
            self.word1 = a // Line A
            self.word2 = b // Line B
            self.word3 = c // Line C
        } //Line BBBB
    
    
        func equal() ->Bool{
            return word1 == word2 + word3
        }
    }
    
    let wordParts = pairOfOptionalAndNonOptionalAndImplicitUnwrapped (a:"partTwo", b: "part", c:"Two")
    wordParts.equal() // Line CCCC
    

    • If I comment out Line A only, I will get no errors, because it is optional, and optionals can be set to nil.
    • If I comment out Line B only, I will get a compilation error on Line BBBB, saying: Return from initializer without initializing all stored properties, I get this because I have declared property word2 as non-optional. I have told the compiler I have guaranteed to have you set...
    • If I comment out Line C only, I will not get an error, unless I actually run a method on my object. The error you could get is: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0) if and only if I run wordParts.equal(), because I told my code that it's an optional meaning that it will be set from elsewhere after instantiation/compilation. Meaning that lldb can through me a runtime error if you it didn't get set. ( the error would happen on line CCCC)

提交回复
热议问题