Sam Zhong
Sam Zhong

Reputation: 21

Why do the variables need to be initialized in class in swift but they don't need to be initialized in struct?

Im new to learn swift.I recently found that the variables or constants are needed to be initialized with an initial number or by the initializer.But in struct they don't need to be initialized?

Upvotes: 1

Views: 349

Answers (2)

CouchDeveloper
CouchDeveloper

Reputation: 19154

An example to @vadian 's answer:

struct S {
    init() {}
    let a: String
}

This will not compile:

Playground execution failed: Test.xcplaygroundpage:11:13: 
error: return from initializer without initializing all stored properties
init() {}
        ^

Upvotes: 1

vadian
vadian

Reputation: 285220

They do need.

From the Swift Language Guide:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

Source: Initialization

Upvotes: 2

Related Questions