-
Notifications
You must be signed in to change notification settings - Fork 264
Description
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 useDocument(), 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.