Skip to content

Error in "Value and Reference Types" article: class Document missing initializer #1268

@kyleqihua

Description

@kyleqihua

In the Swift.org article "Value and Reference Types in Swift" (https://www.swift.org/documentation/articles/value-and-reference-types.html), the reference-type example uses a class Document defined as:

class Document {
    var text: String
}
var myDoc = Document(text: "Great new article")
var friendDoc = myDoc
friendDoc.text = "Blah blah blah"
print(friendDoc.text)
print(myDoc.text)

In Swift, classes do not receive a synthesized memberwise initializer. Because the stored property text has no default value, the compiler does not automatically generate an initializer, so the call Document(text: "Great new article") fails to compile with an error such as "Class 'Document' has no initializers". To make this example compile, either:

  • Provide a default value for text, e.g. var text: String = "" and then use Document(), or
  • Define an explicit initializer: init(text: String) { self.text = text }.

As written, the code misleads readers into thinking that classes get memberwise initializers like structs. It would be helpful to update the article to either add an initializer or default value in the class example, or clarify this difference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions