Chapters

Hide chapters

Swift Apprentice: Beyond the Basics

Second Edition · iOS 18 · Swift 6 · Xcode 16.2

Section I: Beyond the Basics

Section 1: 13 chapters
Show chapters Hide chapters

2. Custom Operators, Subscripts & Keypaths
Written by Ehab Amer

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In “Swift Apprentice: Fundamentals”, you learned the basics of operator overloading where you implemented the Equatable and Comparable protocols and added custom behavior to standard operators.

However, there are certain cases when overloading standard operators isn’t sufficient. This chapter will show you how to create custom operators from scratch and define your own subscripts. You’ll use subscripts as shortcuts for accessing the elements of custom types and provide keypaths as dynamic references to properties in your types.

Custom Operators

You declare an operator when you want to define custom behavior not covered by one of the standard operators. Think of exponentiation, for example. You could overload the multiplication operator since exponentiation means repeated multiplication. But this would be confusing. Operators should do only one type of operation, not two.

You’ll define an exponentiation operator, first only for a specific type, then extend it by making it generic. Before doing that, you need to know some theory about operator types. Time to dive in!

Types of Operators

There are three major types of operators: unary, binary and ternary.

Your Own Operator

Let’s walk through the process of creating a new operator from scratch. You’ll create one for exponentiation. Since it’s a custom one, you can choose the name yourself. It’s usually best to stick to the characters /, =, -, +, !, *, %, <, >, &, |, ^ and ?, although many other Unicode characters are allowed. You may need to type it often, so the fewer keystrokes, the better. Since exponentiation is repeated multiplication under the hood, choosing something that reflects that is good. You’ll use ** since other languages also use this notation.

Compound Assignment Operator

Most built-in operators have a corresponding compound assignment version. Do the same for the exponentiation operator:

Mini-exercises

  1. Implement a custom multiplication operator for strings so that the following code works:

Generic Operators

You want the exponentiation operator to work for all integer types. Update your operator implementations as follows:

Precedence and Associativity

Your shiny new custom operator seems to work just fine, but if you use it in a complex expression, Swift won’t know what to do with it:

Subscripts

You’ve already used subscripts in “Swift Apprentice: Fundamentals - Chapter 7: Arrays, Dictionaries & Sets” to retrieve the elements of arrays and dictionaries. It’s high time you learned to create your very own subscripts. Think of them as overloading the [] operator to provide shortcuts for accessing elements of a collection, class, structure or enumeration.

Subscript Parameters

You don’t have to use names for the subscript’s parameters when calling the subscript, even if you don’t use underscores when declaring them.

Static Subscripts

You can define static subscripts for custom types in Swift:

Dynamic Member Lookup

You use dynamic member lookup to provide arbitrary dot syntax to your type.

Keypaths

Keypaths enable you to store references to properties. For example, this is how you model the tutorials on our website:

Appending Keypaths

You can make new keypaths by appending to existing ones like this:

Setting Properties

Keypaths can change property values. Suppose you set up your very own jukebox to play your favorite song:

Keypath Member Lookup

You can use dynamic member lookup for keypaths:

Keypaths as Functions

You can use keypaths as functions if the function is a closure with only one parameter and the keypath’s returned type matches the returned type of the closure:

Challenges

Before moving on, here are some challenges to test your custom operators, subscripts and keypaths knowledge. It’s best to try and solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.

Challenge 1: Make It Compile

Modify the following subscript implementation so that it compiles in a playground:

Challenge 2: Random Access String

Write a subscript that computes the character at a specific index in a string. Why is this considered harmful?

Challenge 3: Generic Exponentiation

Implement the exponentiation generic operator for float types so that the following code works:

Challenge 4: Generic Exponentiation Assignment

Implement the exponentiation assignment generic operator for float types so that the following code works:

Key Points

  1. Remember the custom operators mantra when creating brand new operators from scratch: With great power comes great responsibility. Make sure the additional cognitive overhead of a custom operator introduces pays for itself.
  2. Choose the appropriate type for custom operators: postfix, prefix or infix.
  3. Don’t forget to define any related operators, such as compound assignment operators, for custom operators.
  4. Use subscripts to overload the square brackets operator for classes, structures and enumerations.
  5. Use keypaths to create dynamic references to properties.
  6. Use dynamic member lookup to provide type-safe dot syntax access to properties.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now