简体   繁体   中英

Unable to declare a constant as optional in swift?

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

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.

你必须这样写-

var name = String()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM