Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Structs

A Swift struct is basically a group of data, organized into properties, as well as methods that do something to or with those properties. There is more to come, but we'll start there for the sake of simplicity.

Let's set up a struct called Locomotive (note the capitalized name):

struct Locomotive 
{
var name: String?
var built: Int?
var museum: String?

func infoString() -> String
{
var infoString = "Name: \(name). Built: \(built)."
if let museum = museum
{
infoString += " Museum: \(museum)."
}
return infoString
}
}

So, we have defined a struct that has three variable properties (with lowercase names), all of which are declared as optionals. Because those properties are permitted to be nil, we can initiate a Locomotive object without actually passing it any value for its properties:

let loco1 = Locomotive() 

However, we are more likely to use the automatically defined initializer, with values for each of its properties:

let loco2 = Locomotive(name: "E111", built: 1964, museum: nil) 

The Locomotive struct has one method, infoString, which returns a simple summary of its properties. You might have noticed that we did not need to refer to self to use the museum property in the body of the method (although you can, for clarity's sake, and it is sometimes necessary to do so, which we'll see later).

Method or function?
As far as Swift is concerned, a function that belongs to a data structure such as class or struct is called a method of that structure. This book will stick to that convention, which is widely adopted in the context of object-oriented programming.

Let's define a struct that has non-optional properties:

struct Driver 
{
var name: String
var yearOfBirth: Int
}

All non-optional properties need to be initialized to some value, and so calling the initializer with no arguments will not compile. We need to supply a complete set of arguments to the initializer:

let driver = Driver(name: "Jones", yearOfBirth: 1964) 

Once again, we see the emphasis placed on safety by the Swift design team: you can't create a broken struct.

Note that we didn't need to write these initializers ourselves (although we can if there is reason to); they are created for us by Swift. Apple calls this memberwise initialization.

We haven't mutated any of our struct properties after it has been created yet, nor have we used many other powerful features available to us. There is a lot more to be said about the struct, and I promise it will be, but for the moment we will put struct to one side in order to take a look at class, a struct reference-value sibling (or at least a close cousin).