Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

swift - Why do I have to use the optional "?" in this code?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Think about what you would get if you try to access the response before you assign it:

let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
print(cheeseQuestion.response) // what would this print?

It's gotta be some kind of a value, right? The value that makes the most sense is something that represents "this question has no response yet", which is what nil is - the absence of a value. Making response optional has the side effect of making its default value nil.

If you don't want it to be optional, that's fine too, but you have to give it a default value (not nil, only optionals can have nil as a value!)

class SurveyQuestion {
    var text: String
    var response: String = "some default response"
    init(text: String) {
        self.text = text
    }
}

or you can initialise it in the initialiser:

init(text: String) {
    self.text = text
    self.response = "some default response"
}

or you can add a parameter to the initialiser and initialise it to that:

init(text: String, response: String) {
    self.text = text
    self.response = response
}

Essentially, if response is not optional, it needs to have some value that is not nil when its initialiser finishes running.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...