In this episode of the Swift introduction series we’ll be looking at classes in Swift.
Swift is a language that supports both functional and object oriented
concepts. Classes are defined with the
class keyword and the body is
surrounded in braces.
Objects can have instance variables specified as either
var or constants
let inside the block. As with other variables, the type can be
explicitly declared or can be inferred by an initial value:
Non-optional values need to be initialized in-line, or in an initializer.
Once the class is defined then can be created using a type constructor. Instance properties can be accessed using dot syntax:
Class types use pass-by-reference semantics; two variables can point to the same instance, so if one variable is used to change the value, then it is seen through the other variable as well:
Instance functions can be added to a class. As a result, it’s possible to add a
fullName method that returns the concatenation of the first and last names:
A special kind of function can be created which is used at class creation time, called the initializer. Fields that are assigned in the initializer do not need to be initialized at the declaration. However, they do need to be declared for a type perspective:
The arguments are implicitly named; if you try and call it without passing in
names (such as
Person("Alex", "Blewitt")) then Swift will complain that the
labels are missing. This can be fixed by using an underscore
_ in front of the
labels of the
init, which instructs Swift to not consider them named:
With Swift 1.1 (released as part of Xcode 6.1) the initializers can now be
failable, implying that they can return
nil if the arguments do not permit
Since the initializer may return
nil the return type is treated as an
Optional which means that it can be used in an
if let construct or
equivalent. Note that in Swift 1.1 there is an error message “all stored
properties of a class instance must be initialized before returning nil from an
initializer” which is a little bit crazy; it’s like saying that you have to
be able to fully construct the object anyway even if the arguments don’t make
sense. Hopefully that will be fixed in a future version.
We’ll go into more detail about classes in future episodes. In next week’s episode, we’ll look at how to create structs in Swift. To subscribe to this series, add the Swift tag feed to your reader.