-1

I have below code.I am trying to declare a 'name' constant as optional but it does not allow it gives error as

stored property 'name' without initial value prevents synthesized initializers

class VideoMode {

    let resolution = Resolution()
    var interlaced = false
    var frameRate:Float = 0.0
    let name: String?
}

EDIT:Why i am getting such error as in case of structure it will not give any error

iOSGuy
  • 171
  • 1
  • 14
  • 4
    A 'nil' constant which never will change is nonsensical. – vadian Jan 22 '17 at 17:03
  • 1
    I'm voting to close this question as off-topic because it is just too something-or-other – matt Jan 22 '17 at 17:05
  • @matt, "Too something-or-other?" LOL. Too silly, perhaps? – Duncan C Jan 22 '17 at 17:07
  • I consider it as a valid question. Valid, concrete issue, clearly stated, code shown. – shallowThought Jan 22 '17 at 17:08
  • 3
    @matt: Why do you vote to close as off-topic *and* answer it? Related: http://meta.stackoverflow.com/questions/262573/why-shouldnt-i-answer-off-topic-questions-faq: *"Answering off-topic questions, promotes the idea that these questions are acceptable questions to ask, thus leading to more off-topic questions."* – Martin R Jan 22 '17 at 17:15
  • 1
    Related: [Why optional constant does not automatically have a default value of nil](http://stackoverflow.com/q/37400196/2976878) – Hamish Jan 22 '17 at 17:19
  • @MartinR For the same reason that you do. – matt Jan 22 '17 at 17:20

2 Answers2

2

You have to say

var name: String?

or you must assign name a value or have an initializer (init) that initializes name.

Thus, this is legal:

class VideoMode {
    let name: String?
    init(name:String) {self.name = name}
}

and this is legal:

class VideoMode {
    let name: String? = "howdy"
}

but this is not legal:

class VideoMode {
    let name: String? // compile error
}

The reason is obvious. If name is a let, and you don't initialize it, it can never be set, because it is a constant. The compiler won't let that sort of silly situation exist.

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

You have to write like this-

var name = String()