Creating classes
Consider the following class definition in Swift:
class Person {
var firstName: String var lastName: String
init(firstName: String, lastName: String) { self.firstName = firstName
self.lastName = lastName
}
var fullName: String {
return "(firstName) (lastName)"
}
}
let john = Person(firstName: "Johnny", lastName: "Appleseed")
That’s simple enough! It may surprise you that the definition is almost identical to its struct counterpart. The keyword class is followed by the name of the class, and everything in the curly braces is a member of that class.
But you can also see some differences between a class and a struct: The class above defines an initializer that sets both firstName and lastName to initial values. Unlike a struct, a class doesn’t provide a memberwise initializer automatically — which means you must provide it yourself if you need it.
If you forget to provide an initializer, Swift will flag that as an error:
Default initialization aside, the initialization rules for classes and structs are very similar. Class initializers are functions marked init, and all stored properties must be assigned initial values before the end of init.
There is actually much more to class initialization than that, but you’ll have to wait until the next chapter, "Advanced Classes", which will introduce you to the concept of inheritance and the effect it has on initialization rules. For now, you’ll get comfortable with classes in Swift by working with basic class initializers.