For the More Curious: Custom Operators

Swift allows developers to create custom operators. This feature means that you can create your own operator to signify, for example, that one instance of the Person type has married another instance. Say, for example, you want to create a +++ function to marry one instance to another.

Create a new Person class, like so:

Example 25.16. Setting up a Person class
...
class Person {
    var name: String
    weak var spouse: Person?

    init(name: String, spouse: Person?) {
        self.name = name
        self.spouse = spouse
    }
}

The class has two properties: one for a name and another for a spouse. It also has an initializer that will give values to those properties. Note that the spouse property is an optional, to indicate that a ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.