How to create custom operators and do operators overloading in Swift

What is the operator.

An operator is a special symbol that you use with one or more values to produce a specific result. For example, the addition operator (+) adds two numbers and resulting in the sum between those two, as in let i = 1 + 2 .

You can think of it as a function with a unique name that can call in unusual places such as front, between, and after the value. You will see in the later section how creating a custom operator is similar to creating a function.

Before we begin to override or create a custom operator, let's learn how many types of operators we have in Swift. Which one that we can override and some limitation when we want to create a custom one.

You can easily support sarunw.com by checking out this sponsor.

Offline Transcription:

Offline Transcription: Fast, privacy-focus way to transcribe audio, video, and podcast files. No data leaves your Mac.

Types of operators

We can categorize operators into three groups. Unary operators Binary operators Ternary operators

Unary operators

Unary operators operate on a single target such as -1, !booleanValue. Unary can appear in two places.

  • Unary prefix operators which appear immediately before their targets such as negative value ( -2 ) and logical not operator ( !booleanValue ).
  • Unary postfix operators which appear immediately after their target such as force unwrapping ( optionalValue! ).

We can overload and create a custom prefix and postfix operator.

Binary operators

Binary operators operate on two targets (such as 2 + 3). It can only appear in between their two targets, infix operator .

We can overload and create a custom infix operator.

Ternary operators

Ternary operators operate on three targets, such as the ternary conditional operator (a ? b : c).

We can't overload or create this kind of operator.

Not every type of operator can be overload. There are four restrictions that I know of:

  • You can't overload and create a custom ternary operator.
  • You can't overload the default assignment operator ( = ). You can overload other binary operators, including compound assignment operators such as a += 2.
  • Only a subset of the ASCII characters are supported. You can check the full list here .
  • Some characters and combinations are reserved for some operators. You can check the full list here .

Since we can't overload or create ternary operators, that left us with three kinds of operators to play with: Prefix Postfix Infix

Now that we know its limitation, let's try overloading existing operators, then defining your own.

Overloading the existing operators

Operator overloading lets us declare multiple operators of the same name with different implementations, in this case, different operands [1] and return type.

Let's start with overloading infix operators.

Overload new operator on strings

Swift supports the four standard arithmetic operators for all number types:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

Swift string doesn't support the * operator, but we will overload the * operator to work on it. We will overload the * operator to take string and integer as arguments and produce a new string representing the given string repeated the specified number of times. The result will look like this:

As I mentioned before, you can think of operators as a function with a special name. To declare overloading operators, we would do just that.

Declare as a global function You can declare it as a global function like this.

Declare as static function of a class or struct You can declare it as a static function under a class or struct. I prefer this form since it shows that the operator is a part of string capability (This is also how Swift declare the + operator on the string)

<1> We declare an infix operator that works on two operands, string, and integer, and returns a new string. <2> We create a new string representing the given string repeated the specified number of times.

Again, here is the result:

Overload existing operators with different arguments.

Swift string already overloading + operators, which concatenated two strings together.

We will overload the + operator with a different argument. Our new overloading operates on string and integer and produces a string with the last character repeated equals to the second operands.

<1> Try to get the last character. <2> Concatenate the string with the repeated last character.

To overloading a prefix operator, we need to add a prefix keyword before a func .

In the following example, I overload the - unary operator for a string, which will reverse the characters in a given string.

<1> We add the prefix keyword to tell the compiler that this is intended to use as a prefix operator.

And here is the result:

To overloading a postfix operator, we need to add a postfix keyword before a func .

In the following example, I overload ... unary operator for string which will append "..." string at the end of the given string.

<1> We add the postfix keyword to tell the compiler that this is intended to use as a postfix operator.

Adding a custom operator

If the existing operators are not enough for you, Swift allows you to define a new operator. We will create a new operator called 🦄 Unicorn operator ( .^. ). Then we will make this operator operate on a string. The unicorn operator will insert a rainbow emoji 🏳️‍🌈 according to the operation position (prefix, postfix, infix).

The first thing we need to do is telling Swift about our new operator. We will start with the infix version of our Unicorn operator.

This is a syntax to declare a new infix operator.

That's all we need to do. Now Swift knows about our new operator. We can use it the same way as we did with operator overloading.

<1> We overload our new operator with string operands. <2> Our Unicorn operator will insert a rainbow flag between two operands.

It is not much different on how to declare an infix operator. The only difference we need to make is changing the keyword from infix to postfix .

This is a syntax to declare a new postfix operator.

Then we use it just like before.

<1> We append a rainbow flag at the end of the string.

You might be able to guess. Here is how we declare a new prefix operator.

And here is how we implement it.

<1> We prepend a rainbow flag at the beginning of the string.

The difference between overload existing operator and a custom one

As you can see, the only difference between an overload existing operator and a custom one is declaring a new operator . If you are failing to do so, the compiler will give you this error.

Operator implementation without matching operator declaration error

It might be debatable about this Swift feature whether you should use it or not. In the end, it all about trades off. Using this feature would save you from some boilerplate code but might cause poor code readability since you introduce a new syntax and implementation to the existing operators. I think you would find a fair use case out of it when the time comes.

I also leave out some implementation detail of declaring a new operator, Operator Precedence and Associativity. I think it deserves its own article and I might write about it in the future. If you don't want to miss it, Subscribe or Follow me on Twitter and get notified.

Related Resourcess

  • Advanced Operators
  • Lexical Structure - Operators , List of characters that can be used to define custom operators.
  • Operator Declarations

The values that operators affect are operands . In the expression 1 + 2, the + symbol is a binary operator, and its two operands are the values 1 and 2. ↩︎

You may also like

  • Swift Ternary operator (?:) 09 Feb 2023
  • What does the ?? operator mean in Swift 30 Sep 2021
  • What is Swift If Case 30 Nov 2022
  • How to join an Array of strings into a Single string in Swift 28 Dec 2022
  • How to use SwiftUI in UIKit 26 Jul 2019
  • Sign in with Apple Tutorial, Part 2: Private Email Relay Service 22 Dec 2019

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter. Every Friday , you'll get a quick recap of all articles and tips posted on this site . No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Part 2 in the series "Building Lists and Navigation in SwiftUI". We will explore a ScrollView, UIScrollView equivalent in SwiftUI.

Part 3 in the series "Building Lists and Navigation in SwiftUI". We will explore a List, UITableView equivalent in SwiftUI.

  • Sponsorship
  • Become a patron
  • Buy me a coffee
  • Privacy Policy

Digital Bunker

Overloading & Creating New Operators In Swift 5

We'll cover everything you need to know about operator overloading and creating custom operators with unique precedence and associativity behavior.

Operator overloading allows you to change how existing operators (e.g. + , - , * , / ,  etc.) interact with custom types in your codebase. Leveraging this language feature correctly can greatly improve the readability of your code.

Let’s say we had a struct to represent Money :

Now, imagine we’re building an e-commerce application. We’d likely need a convenient way of adding up the prices of all items in our shopping cart.

With operator overloading, instead of only being able to add numeric values together, we could extend the + operator to support adding Money objects together. Moreover, as part of this implementation, we could even add logic to support adding different currency types together!

In order to take advantage of this language feature, we just need to provide a custom implementation for the operator in our type's implementation:

You may have even used operator overloading without realizing it. If you've ever implemented the Equatable protocol, it requires you to provide a custom implementation for the == operator:

I hope you'll agree that, in these examples, operator overloading has increased the code's readability and expressiveness. However, we should be careful not to overdo it.

Whenever you're creating or overriding an operator, make sure its use is obvious and undisputed. Language features like this often produce diminishing returns, as the more custom behavior we introduce, the harder it is for other developers to understand our code.

Creating Custom Operators

Whenever we're discussing custom operators, overloading an existing operator is always going to be the easier option. Assuming, of course, this doesn't compromise the code's legibility.

Instead, if we want to create our own operator, we'll need to specify 3 additional pieces of information: the type of the operator, the precedence order, and the associativity behavior.

When we're simply overloading an existing operator, we inherit all of this information from the parent operator directly.

Operator Types

When we want to create our own operator, we’ll need to specify whether it's of the prefix , postfix , or infix variety.

prefix - describes an operator that comes before the value it is meant to be used with (e.x. !isEmpty )

postfix - describes an operator that comes after the value it is meant to be used with (e.x. the force-unwrapping operator - user.firstName! )

prefix and postfix are also referred to as "unary” operators as they only affect a single value.

infix - describes an operator that comes in between the value it is meant to be used with and is the most common type (e.x. + , - , / , * are all infix operators)

infix are also referred to as "binary” operators since they operate on two values.

For the statement - 2 + 5 x 5  - we know that the answer is 2 + (5 x 5) => 27 because the precedence of the operators involved tell us the order in which to evaluate the expression.

In the same way that the higher precedence of multiplication resolves the ambiguity in the order of operations here, we need to provide the compiler with similar information when we create a custom operator.

By specifying the precedence, we can control the order in which the expression is evaluated as operations belonging to a higher precedence group are always evaluated first.

We'll see how to specify the precedence of our operator shortly, but let's understand the current state of affairs in Swift first.

The following image shows a list of all precedence group types in Swift from the highest priority to the lowest priority:

swift assignment operator overloading

If you declare a new operator without specifying a precedence group, it is a member of the DefaultPrecedence precedence group which has no associativity.

Associativity

The associativity of an operator is simply a property that specifies how operators of the same precedence level are grouped in the absence of parentheses.

Imagine we have an expression with multiple operators all belonging to the same precedence level:

We could process this expression in 2 different ways:

(20 / 2) / 5

20 / (2 / 5)

which would give us 2 and 50 , respectively.

This ambiguity is exactly what the operator's associativity helps us resolve.

An operator can be associative (meaning the operations can be grouped arbitrarily), left-associative (meaning the operations are grouped from the left), and right-associative (meaning the operations are grouped from the right).

In the simplest terms, when we say an operator is left-associative we simply evaluate our expression from left to right. Conversely, for a right-associative operator, we evaluate our expression from right to left.

As another example, we know that * , / , and % all have the same precedence, but by changing their associativity, we can get wildly different results:

Left-Associative

(4 * 8) / 2 % 5 ==> (32 / 2) % 5 ==> 16 % 5 ==> 1

Right-Associative

4 * 8 /(2 % 5) ==>  4 * ( 8 / 2) ==> 4 * 4 ==> 16

Put differently, operator associativity allows us to specify how an expression should be evaluated when it involves multiple operators of the same precedence group.

All arithmetic operators are left-associative.

In order for expressions involving our custom operator to evaluate correctly, we'll need to be mindful of both the operator's precedence and associativity behavior.

Creating A Custom Operator

With all of the theory out of the way, let's create a custom operator that will allow us to easily perform exponentiation.

Since exponentiation has a higher precedence than multiplication and is right-associative, we'll need to create a new precedence group as this operation doesn't match any of Swift's existing precedence group options.

We'll create the precedencegroup by filling in the relevant fields from this template:

Next, we need to let the compiler know about the existence of our custom operator and specify its behavior:

And now, anywhere else in our code we're free to use our custom operator:

2 ^^ 8 => 256.0

It's important to mention here that our precedence group declaration and all operator declarations and functions must be placed at the file scope - outside of any enclosing type. Don't worry if you forget this, the compiler will dutifully remind you.

Limitations Of Operator Overloading

There are a few additional caveats to mention.

While ternary operator types (e.g. var userStatus = user.age >  18 ? .approved : .rejected ) also exist in Swift, the language does not currently allow for overloading their operation.

This same restriction applies to the default assignment operator ( = ) and the compound assignment operator ( += ).

Otherwise, all operators that begin with / , = , - , + , ! , * , % , < , > , & , | , ^ , ? , or ~ , or are one of the Unicode characters specified here are fair game.

Best Practices

While this language feature is extremely powerful and go a long way towards improving your code's legibility and friendliness, it can also take you in the opposite direction.

Let's take a moment to discuss some best practices around using this language feature.

Firstly, overloading operators in Swift should be done in a way that is consistent with how the operator is normally used. A new developer should be able to reason about the expected behavior of the operator without needing to check the implementation.

Next, in situations where the traditional operators don't make semantic sense, you may want to consider creating a custom operator instead.

Finally, and a more pragmatic point, they should be easy to remember and type on the keyboard - an obscure custom operator like .|. benefits no one as its meaning is neither intuitive nor is it convenient to type.

Ultimately, this is just a long-winded way of saying that custom operators, typealias , and all other forms of "syntactic sugar" can improve your code's clarity and your development speed when used with a bit of restraint and pragmatism.

If you're interested in more articles about iOS Development & Swift, check out my YouTube channel or follow me on Twitter .

Join the mailing list below to be notified when I release new articles!

Do you have an iOS Interview coming up?

Check out my book Ace The iOS Interview !

Further Reading

Want to take a deeper dive into operator overloading?

Check out these great resources:

  • https://www.codingexplorer.com/custom-operators-swift/
  • https://sarunw.com/posts/how-to-create-custom-operators-and-operators-overloading-in-swift/
  • https://jayeshkawli.ghost.io/custom-operators-in-swift/

Subscribe to Digital Bunker

This page requires JavaScript.

Please turn on JavaScript in your browser and refresh the page to view its content.

logo

You’ve made it this far. Let’s build your first application

DhiWise is free to get started with.

Image

Design to code

  • Figma plugin
  • Documentation
  • DhiWise University
  • DhiWise vs Anima
  • DhiWise vs Appsmith
  • DhiWise vs FlutterFlow
  • DhiWise vs Monday Hero
  • DhiWise vs Retool
  • DhiWise vs Supernova
  • DhiWise vs Amplication
  • DhiWise vs Bubble
  • DhiWise vs Figma Dev Mode
  • Terms of Service
  • Privacy Policy

github

Insights into Swift Operator Overloading: Enhancing Code Expression

Authore Name

Nidhi Sorathiya

Frequently asked questions, is there operator overloading in swift, what is overloading and overriding in swift, how to overload the default assignment operator (=) in swift, what does the === operator do in swift, what is a custom operator in swift.

Swift operator overloading allows developers to redefine how operators behave with various data types, offering flexibility and expressiveness in code.

We’ll delve into the mechanics of operator overloading, covering existing operators and the creation of custom ones. This power feature enables writing clean, intuitive code that can be tailored to specific programming needs, making Swift a dynamic tool for developers. Join us to unlock the potential of operators in Swift and enhance your coding skills.

Fundamentals of Swift Operator Overloading

In Swift, operator overloading is the process where you provide a custom implementation of an existing operator, such as the addition operator (+), or present an entirely new operator, to work with the types you define. This process not only increases the readability and conciseness of your code but also enables the performance of complex operations in a simplified manner.

Operator overloading in Swift uses specific keywords and syntax to redefine the operator's functionality. When you overload an operator, you tell the compiler how to use that operator with your custom types. The overloading operators must be marked with the static keyword and can be defined within class, struct, or enum types to perform operations that involve their instances.

Swift provides a comprehensive set of operators, which are categorized as unary, binary, and ternary:

• Unary operators operate on a single target. These include unary prefix operators, such as the logical NOT operator (!), and unary postfix operators, like the increment operator (++) that Swift deprecated in favor of the += 1 operation.

• Binary operators work with two values and include common operators like the addition and subtraction operators (+ and ``).

• The ternary conditional operator is a unique operator in Swift that works with three targets. The ternary conditional operator (?:) is the only ternary operator in Swift.

Key benefits of using operator overloading include:

• Improving code readability by allowing complex operations to be expressed succinctly

• Adding custom behavior to existing operators, tailoring them to work with your custom types

• Facilitating the implementation of domain-specific languages within your applications

While redefining operators might seem straightforward, developers should employ operator overloading judiciously. Overuse or inappropriate application of operator overloading can lead to code that's hard to understand and maintain. Therefore, it is essential to adhere to logical and conventional meanings of operators while engaging in operator overloading to maintain code clarity.

Exploring Operators in Swift

Before delving into the intricacies of Swift operator overloading, it's crucial to recognize the fundamental role of operators in the Swift programming language. Operators are special symbols or phrases that you use to check, change, or combine values. Swift supports most standard arithmetic operators and improves upon them with enhanced functionality such as overflow operators and compound assignment operators.

The arithmetic operators (addition + , subtraction - , multiplication * , and division / ) are familiar to most programmers and are often the first that come to mind. Additionally, Swift includes a range of comparison operators such as == , != , > , < , >= , and <= that compare two values and return a Bool. Beyond these common operators, Swift provides operators that aren't as universally known or used, such as the nil coalescing operator ( ?? ) and range operators ( ..< and ... ).

Understanding how these operators function is the prerequisite for comprehending operator overloading. The operators in Swift are generally categorized into:

Unary operators (a): An operator that prefixes (!b) or postfixes (i++) a single operand.

Binary operators (a + b): An operator that is placed between two operands and inflicts some form of computation or logical operation.

Ternary operators (a ? b : c): An operator that works with three parts, the most famous example being the ternary conditional operator which evaluates a condition to return one of two values.

Swift emphasizes safety and performance, and the design of its operator system follows the same philosophy. A well-defined precedence and associativity for each operator ensures that complex expressions can be evaluated predictably without the need for excessive parentheses.

The Syntax for Swift Operator Overloading

Swift operator overloading requires developers to become familiar with a syntax specifically designed for this feature. Overloading an operator involves creating a function with a special name, that name being the operator we wish to overload, and implementing our custom behavior within it. These functions need to be marked as static and placed within the appropriate scope—whether that's a class, struct, or enum definition—since they pertain to the type itself rather than its instances.

Overloading Existing Operators

To overload an existing operator, you declare and implement a static method with the name of the operator as the function's name. It’s defined using the operator keyword, followed by the operator itself within a pair of parentheses. For example, overloading the addition operator for a custom Vector type would look like this:

Creating Swift Custom Operators

When defining custom operators, first declare the operator using the prefix, infix, or postfix keywords to specify the type of operator you're creating. Next, you need to define its functionality similarly to how you overload an existing operator, but with the new operator's symbol. Custom operators can include characters like / , = , - , + , ! , * , % , < , > , & , | , ^ , ? , and ~ .

Here's an example of declaring and implementing a custom infix operator ** for exponentiation:

In the example, we also define a precedence group, another important aspect of infix operators. This defines how your custom infix operator interacts with others regarding operator precedence and associativity rules.

Overall, when overloading operators, you must collaborate with Swift's type system to ensure that the compiler interprets your overloads correctly. It’s necessary to specify the types of the operands and the return type accurately to avoid any ambiguity. Whether you're overloading operators for existing types or your custom types, Swift’s structure for operator overloading demands precision and foresight, ensuring your custom operators function seamlessly in various contexts.

Dive into Custom Operators

Swift goes a step beyond enabling the overloading of existing operators by allowing developers to define custom operators. This means you can create an operator symbolically represented in a way that makes sense for your code’s context. These custom operators can then be overloaded with specific functionality related to your data types.

What Are Swift Custom Operators?

Custom operators are new symbols that you introduce as operators in your code. These can serve to make expressions more readable and concise, particularly when you’re performing operations that are unique to your program's domain. Swift custom operators can be defined with the prefix, infix, or postfix notation, depending on how they are used relative to their operands.

Declaring and Implementing Custom Operators in Swift

To declare a custom operator, you use the operator keyword followed by the operator symbol and a prefix, infix, or postfix modifier, depending on how the operator should be used. Once declared, you must also define the operator's functionality by implementing a function with the same symbol, appropriately marked with the static keyword as it relates to the type itself.

In the code snippet above, we’ve created a new prefix operator +++ that increments an integer by 2.

Practical Examples of Custom Operators Usage

Using custom operators can significantly cut down boilerplate code and provide a level of abstraction similar to that of functions or methods. Suppose you’re working on a graphics-related application where manipulating pixel data is common. A custom operator for combining color values could streamline the process:

This mixture operator <+> succinctly expresses the idea of combining two colors, something that might otherwise require a more verbose function or method call.

Custom operators are a powerful feature in Swift, allowing us to write code that's more aligned with the domain we're working in. However, they should be used judiciously to ensure that code remains approachable and intuitive for other developers.

In our next sections, we will dive deeper into the overloading of specific types of operators and discuss their importance and implications by exploring prefix, infix, and ternary conditional operator overloading in Swift.

Defining Prefix and Postfix Operators

Swift’s prefix and postfix operators function with only a single operand and are known for their clarity and efficiency when implemented correctly. The prefix operator appears before its operand, while the postfix operator follows it. Consider the unary minus (-) as a prefix or the increment (++) as a postfix in other programming languages.

Understanding Prefix Operator Overloading

Let's look at an example of how to overload a prefix operator in Swift. A common scenario might involve negating some property of a custom type:

In this instance, we define and implement the unary minus operator for a custom Currency type to convey the concept of debt.

Case Study: Implementing a Prefix Operator

To further illustrate, consider a graphics application where you might want to invert colors. A prefix operator could be an ideal way to express this action:

Here, the ~~ operator has been created to cleanly signify the inversion of a color.

Implementing Infix Operators

Infix operators are those that are written between their two operands, such as the multiplication ( * ) and division (/) operators. New infix operators must provide precedence and associativity to dictate how they interact with other infix operators.

The Role of Infix Operator Overloading in Swift

The true power of Swift comes into play when you combine custom types with infix operator overloading. This can create notations that are highly expressive and domain-specific, which improves both code readability and functionality.

For instance, let's say you have a custom-type Fraction that represents a mathematical fraction:

The custom infix operator %% can be used to add two Fraction instances together with appropriate logic inside the implementation.

Rules for Infix Operator's Precedence and Associativity

When creating new infix operators, you must specify their precedence and associativity:

Here, the *** operator is given the same precedence as standard multiplication, ensuring expressions involving both are evaluated in the expected order.

Precedence and Associativity in Infix Operators

To manage the complexity of expressions with multiple operators, Swift uses precedence and associativity rules. When creating custom infix operators, it's essential to define where they stand in the operator hierarchy to ensure the correct order of operations.

Establishing Precedence for Infix Operators

Precedence in Swift dictates the order in which operations are performed in a compound expression. Every infix operator belongs to a precedence group, which determines this order. When you create a custom infix operator, you should assign it to a precedence group to define how it interacts with other infix operators.

Here's an example of establishing a custom infix operator for vector cross-product with its precedence:

In the example above, the new operator >< for cross-product takes its place in the precedence hierarchy, ensuring it evaluates correctly in mixed expressions.

Understanding Precedence and Associativity Rules

Operator precedence dictates which operator is applied first in an expression, while associativity decides the grouping of operators with the same precedence.

For example:

In expressions with operators of the same precedence group, associativity becomes important:

Overloading the Ternary Conditional Operator

Swift only includes one ternary operator: the ternary conditional operator ? :, which is used to choose between two expressions based on a given condition. Because of its unique nature and established behavior, the ternary conditional operator is not overloadable in Swift. This restriction is intentional to preserve the readability and predictability of ternary conditionals—constructs that developers rely upon to be consistent in their function.

Can You Overload the Ternary Conditional Operator?

Currently, overloading the ternary conditional operator is not supported in Swift. Attempting to do so would complicate the language's grammar and introduce ambiguity, making code harder to understand and maintain.

Why Overloading the Ternary Conditional Operator is Rare

Unlike infix, prefix, and postfix operators, the ternary conditional operator has a fixed and well-understood behavior, tightly integrated within the language's syntax. Swift's decision to make it non-overloadable preserves the clear and concise semantics that ternary conditionals are known for.

Operator overloading enhances Swift's customizability and expressive power, but with great power comes great responsibility. It's crucial to use custom operators sparingly and thoughtfully to keep code understandable and prevent confusion. With a robust understanding of precedence, associativity, and restraint, developers can use Swift operator overloading to create powerful and expressive syntax tailored specifically to their domains.

Advanced Swift Operator Overloading Techniques

Overloading operators for custom types can give you powerful ways to express the operations that those types can undergo. As you work with complex data structures or mathematical concepts, you will discover that the ability to provide natural expressions for operations can make your code not only more elegant but also more closely aligned with the domain you're working with.

Overloading Operators for Custom Types

Swift operator overload provides an opportunity to define the behavior of standard operators for your custom types or to create entirely new operators. When adding operator overloading to custom types, consider the types of operations that are integral to the type's function.

Let's take an example where we develop a Matrix type in a linear algebra library:

By overloading the multiplication ( * ) operator, we can provide a matrix multiplication operation directly on Matrix instances, making the library more intuitive.

Ensuring Type Safety with Operator Overloading

Swift’s type system plays a crucial role in operator overloading as it helps maintain type safety. It’s important to ensure that the types your operators work with are handled correctly:

In the code above, we use Swift's guard statement to ensure that we only add matrices of the same dimensions, preserving type safety and reducing potential run-time errors.

Operator overloading in Swift also includes the ability to specify the result type of an overloaded operator, allowing for more complex transformations, as long as they adhere to the rules of the language's type system.

Best Practices for Swift Operator Overloading

Using operator overloading in Swift can make your code more intuitive and concise. However, with such power comes the responsibility to use it wisely. Adhering to best practices ensures that the code is not only performant and reliable but also maintainable and easy to understand.

When to Overload Operators: Practical Guidelines

Overload operators when it can simplify code without sacrificing clarity. Avoid overloading operators in a way that could confuse someone reading your code—operators should do what is expected of them. For example, it makes sense for the + operator to represent addition or concatenation but using it for subtraction would defy convention and lead to confusion.

Adhere to the following guidelines:

• Overload operators when you have a clear and natural meaning for them.

• Consider the mathematical properties of operators (such as commutativity and distributivity) to retain consistency of operations.

• Document your overloaded operators well, explaining how and why they're used.

Pitfalls to Avoid with Swift Operator Overloading

Avoid these common pitfalls when working with Swift operator overloading:

• Overcomplicating expressions by using too many custom operators.

• Violating the principle of least astonishment—don't give operators unexpected behaviors.

• Overloading too many operators for a single type leads to complex and unintelligible code.

Striking the right balance requires a thoughtful approach to design and a thorough understanding of how operator overloading affects code readability and maintainability.

Swift operator overloading is a powerful feature that, when used correctly, can make your code more expressive and tailor it to the problem at hand. We've explored the syntax and semantics of overloading existing operators and creating new custom operators, as well as practices to keep in mind to maintain clean and understandable code.

Incorporate these techniques rudely in your Swift projects and witness the transformation in how you conceptualize and implement logic around data types and operations. Happy coding!

Short on time? Speed things up with DhiWise!!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Operator Overloading in Swift

Apple developer.

In Swift, operator overloading provides a powerful mechanism for extending the functionality of built-in operators to work with custom types. By defining custom implementations for operators like + , - , * , and more, developers can imbue their own types with expressive and intuitive behavior, enhancing code readability and maintainability. In this guide, we'll explore the concept of operator overloading in Swift, understand its syntax and conventions, and delve into practical examples showcasing its versatility and utility.

Introduction to Operator Overloading

Operator overloading allows developers to redefine the behavior of existing operators for their custom types. This means that operators such as + , - , * , and others can be used with user-defined classes and structures, enabling intuitive and concise syntax for performing operations specific to those types.

Syntax of Operator Overloading

In Swift, operator overloading is achieved by defining global functions with the operator keyword followed by the operator to be overloaded. Let's look at a simple example of overloading the addition operator + for a custom Vector type:

In this example, we define a custom Vector structure and then extend it to provide a custom implementation of the addition operator + . This implementation allows us to add two Vector instances together using the familiar + syntax.

Using Operator Overloading

Once operators are overloaded for custom types, they can be used just like built-in operators. Let's see how we can use the custom + operator with our Vector type:

In this example, we create two Vector instances and add them together using the overloaded + operator, resulting in a new Vector instance with the summed components.

Precedence and Associativity

When overloading operators, it's important to consider precedence and associativity to ensure that the behavior is consistent with other operators in Swift. Precedence determines the order in which operators are evaluated in an expression, while associativity determines the grouping of operators with the same precedence. Swift provides default precedence and associativity for many operators, but custom operators can specify their own precedence and associativity using operator declarations.

Practical Examples of Operator Overloading

Operator overloading can be used in a wide range of scenarios to enhance code readability and expressiveness. Some practical examples include:

  • Overloading arithmetic operators for custom numeric types like matrices or complex numbers.
  • Overloading comparison operators ( == , != , < , > , etc.) for custom types to define custom equality or ordering criteria.
  • Overloading bitwise operators ( & , | , << , >> , etc.) for custom bit manipulation operations.

Operator Overloading in Swift Programming

Operator overloading in Swift provides developers with a powerful tool for extending the functionality of built-in operators to work with custom types. By defining custom implementations for operators, developers can create more expressive, intuitive, and concise code, enhancing the readability and maintainability of their Swift codebases. Whether it's arithmetic operations, comparison operations, or bitwise operations, operator overloading allows Swift developers to unleash the full potential of their custom types. Happy coding!

mutating Structs and @Observable Class - Swift

In Swift, you can use both mutating methods in structs and ObservableObject classes to manage state, but they serve different purposes and are used in different contexts. Structs with mutating methods provide a powerful way to work with value types while still allowing for controlled mutability. They are ideal for

AppStorage vs UserDefaults - Storing Data in Swift

Both AppStorage and UserDefaults are used in Swift to store user preferences or small amounts of data, but they serve different purposes and are used in slightly different contexts. 1. AppStorage * Introduced in: SwiftUI * Purpose: AppStorage is a property wrapper that integrates with UserDefaults but is designed to work seamlessly

How does "body: some View" work in SwiftUI?

In SwiftUI, the body: some View syntax is a key part of defining custom views. This syntax leverages the concept of opaque return types introduced in Swift 5.1, which allows the function to specify that it returns some type that conforms to the View protocol, without specifying the exact

Guard with Optionals in Swift

In Swift, guard statements are commonly used with optionals to handle early exits from a function or block of code if certain conditions are not met. The guard statement provides a clean and readable way to unwrap optionals and handle potential failure cases without deeply nesting your code. Using guard

Overloading Custom Operators in Swift

In this Swift tutorial, you’ll learn how to create custom operators, overload existing operators and set operator precedence. By Owen L Brown.

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Already a member of Kodeco? Sign in

Getting Started

Overloading the addition operator, other types of operators.

  • Mixed Parameters? No Problem!
  • Protocol Operators
  • Creating Custom Operators
  • Precedence Groups
  • Dot Product Precedence
  • Where to Go From Here?

Operators are the core building blocks of any programming language. Can you imagine programming without using + or = ?

Operators are so fundamental that most languages bake them in as part of their compiler (or interpreter). The Swift compiler, on the other hand, doesn’t hard code most operators, but instead provides libraries a way to create their own. It leaves the work up to the Swift Standard Library to provide all of the common ones you’d expect. This difference is subtle but opens the door for tremendous customization potential.

Swift operators are particularly powerful because you can alter them to suit your needs in two ways: assigning new functionality to existing operators (known as operator overloading ), and creating new custom operators.

Throughout this tutorial, you’ll use a simple Vector struct and build your own set of operators to help compose different vectors together.

Open Xcode and create a new playground by going to File ▶ New ▶ Playground . Pick the Blank template and name your playground CustomOperators . Delete all the default code so you can start with a blank slate.

Add the following code to your playground:

Here you define a new Vector type with three properties conforming to two protocols. The CustomStringConvertible protocol and the description computed property let you print a friendly String representation of the Vector .

At the bottom of your playground, add the following lines:

You just created two Vector s with simple Array s, and with no initializers! How did that happen?

The ExpressibleByArrayLiteral protocol provides a frictionless interface to initialize a Vector . The protocol requires a non-failable initializer with a variadic parameter: init(arrayLiteral: Int…) .

The variadic parameter arrayLiteral lets you pass in an unlimited number of values separated by commas. For example, you can create a Vector such as Vector(arrayLiteral: 0) or Vector(arrayLiteral: 5, 4, 3) .

The protocol takes convenience a step further and allows you to initialize with an array directly, as long as you define the type explicitly, which is what you’ve done for vectorA and vectorB .

The only caveat to this approach is that you have to accept arrays of any length. If you put this code into an app, keep in mind that it will crash if you pass in an array with a length other than exactly three. The assert at the top of the initializer will alert you in the console during development and internal testing if you ever try to initialize a Vector with less than or more than three values.

Vectors alone are nice, but it would be even better if you could do things with them. Just as you did in grade school, you’ll start your learning journey with addition .

A simple example of operator overloading is the addition operator. If you use it with two numbers, the following happens:

But if you use the same addition operator with strings, it has an entirely different behavior:

When + is used with two integers, it adds them arithmetically. But when it’s used with two strings, it concatenates them.

In order to overload an operator, you have to implement a function whose name is the operator symbol.

Add the following piece of code at the end of your playground:

This function takes two vectors as arguments and return their sum as a new vector. To add vectors, you simply need to add their individual components.

To test this function, add the following to the bottom of your playground:

You can see the resultant vector in the right-hand sidebar in the playground.

The addition operator is what is known as an infix operator, meaning that it is used between two different values. There are other types of operators as well:

  • infix : Used between two values, like the addition operator (e.g., 1 + 1 )
  • prefix : Added before a value, like the negation operator (e.g., -3 ).
  • postfix : Added after a value, like the force-unwrap operator (e.g., mayBeNil! )
  • ternary : Two symbols inserted between three values. In Swift, user defined ternary operators are not supported and there is only one built-in ternary operator which you can read about in Apple’s documentation .

The next operator you’ll want to overload is the negation sign, which will change the sign of each component of the Vector . For example, if you apply it to vectorA , which is (1, 3, 2) , it returns (-1, -3, -2) .

Add this code below the previous static function, inside the extension:

Operators are assumed to be infix , so if you want your operator to be a different type, you’ll need to specify the operator type in the function declaration. The negation operator is not infix , so you add the prefix modifier to the function declaration.

At the bottom of your playground, add the line:

Check for the correct result in the sidebar.

Next is subtraction, which I will leave to you to implement yourself. When you finish, check to make sure your code is similar to mine. Hint: subtraction is the same thing as adding a negative.

Give it a shot, and if you need help, check the solution below!

[spoiler title=”Solution”]

Test your new operator out by adding this code to the bottom of your playground:

All videos. All books. One low price.

A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

Creating custom operators in Swift

swift assignment operator overloading

Table of Contents

What is an operator in swift, types of operators in swift, operator notation, operator precedence and associativity in swift, common operators in swift, defining a custom operator in swift, setting precedence of custom swift operators, specifying the notation of a custom operator in swift.

Operators are one of the basic constructs of any programming language. They are represented as symbols and have various associated properties, and understanding them is crucial to mastering any programming language.

Swift Logo

In this article, we’ll look at some of the operators that Swift ships with and also create our own operators.

Before we begin looking at the different operators that Swift provides us with and creating custom operators, let’s understand a few basic terms related to them. Here’s an example:

Here, we can see a few variables and constants being defined, along with a few symbols (e.g., = and + ). Let’s define two terms here:

  • Operators: any symbol that is used to perform a logical, computational, or assignment operation. = is used to assign and + is used to add in the above example and are therefore operators
  • Operands: variables on which operations are performed, e.g., on line 1 we have a as an operand, and on line 3, we have a and b as two operands on which the + operator is being applied

There are three different types of operators, which are defined by the number of operands they work on.

  • Unary operators: operators that work on only one operand (e.g., = and ! )
  • Binary operators: work on two operands, such as + , - , * , etc.
  • Ternary operator: works on three operands, e.g., ?:

Notation defines the position of the operator when used with the operands. There are again three types:

  • Infix : when the operators are used in between operands. Binary and ternary operators are always infixed
  • Prefix : when the operators are used before an operand, e.g., ++ , -- , and !
  • Postfix : when the operators are used after an operand, e.g., …

When working with operators in Swift, you should also know the priority order in which the operator is executed. Operator precedence only matters for infix operators, as they work on multiple operands.

For example, if an expression has multiple operators in it, Swift needs to know which operator needs to be executed first.

In the above example, * has more precedence compared to + , which is why 6*2 is executed before 4+6 .

In case you have two operators with the same precedence being used in an expression, they’ll fall back on their associativity. Associativity defines the direction in which the expression will start resolving in case the precedence of the operators are the same.

Associativity is of two types:

  • left : this means that the expression to the left will be resolved first
  • right : this means the expression to the right will be resolved first

For example, we have the following statement:

Because both + and - have the same precedence, Swift falls back to the associativity of the operators. + and - have associativity of left , so we resolve the expression from the left so that + is evaluated first.

Here’s a table of the precedence order that Swift follows. The table lists the precedence in the order of decreasing priority.

, , ,
, , , ,
, , , , ,
,
, , ,
, , , , , , , , , , , , , ,
,
, ,
, , , , , , , , , , , , , , , , , ,

Now that we know the basics of what Swift operators are and how they are used, let’s look at popular operators that ship with Swift.

swift assignment operator overloading

Over 200k developers use LogRocket to create better digital experiences

swift assignment operator overloading

The most common operators that Swift ships with fall under the following categories:

1. Assignment operator

Assignment operators are used to assign values to a constant or variable. The symbol is = .

2. Arithmetic operators

These operators are used to perform basic arithmetic operations, such as + , - , * , / , and % .

3. Logical operators

Logical operators are used to combine two conditions to give a single boolean value output, e.g., ! , && , and || .

4. Comparison operators

These operators are used to compare numbers and give out a true or false output: > , < , == , >= , <= , and != .

5. Ternary operator

This operator is a shorthand operator for writing if-else conditions. Even though it does the same job, it is not a good idea to consider it a replacement for if-else conditions because it hampers readability.

Therefore, when you have different code blocks to run for different conditions, it’s better to use if-else blocks. For shorter, simpler cases, use the ternary operator. The operator, ?: , is used like this:

6. Nil coalescing operator

This is a shorthand operator to return default values in case a particular variable is nil. The operator symbol is ?? and commonly used like this:

7. Range operators

These operators are used to define ranges, e.g., … and ..< . They are mainly used with array/strings to extract sub arrays/strings.

For a list of all the basic operators and their descriptions, read the Swift documentation .

Now that we’ve seen the operators that Swift ships with, let’s create our own operators. Custom operators are generally defined for three purposes:

  • To define a completely new operator because you think the symbol’s meaning can express what the operator will do better than a function with a name can
  • To define an operator that exists for basic data types like numbers or strings but does not exist for classes or structs that have been defined by you
  • You want to override an operator that already exists for your classes and structs, but you need it to behave differently

Let’s look at all three purposes with examples.

Creating a new operator with a new symbol

Let’s say you want to define an operator with the △ symbol that calculates the hypotenuse of a right angle triangle given its two sides.

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Creating an operator for a custom class or struct

We know that the + operator is used to add two numbers, but let’s say we wanted to add two instances of our struct called Velocity , which is a two-dimensional entity:

If we were to run the following command, you’d get a compiler error:

In this case, it makes sense to define a + operator that takes care of adding two Velocity instances:

Now the earlier statement will execute properly.

Overriding a Swift operator that already exists for a class/struct

Let’s say you have a struct that is used to define an item in a supermarket.

When we need to compare two items, such that if two items have the same itemName , itemType , and itemPrice , we need to consider them equal regardless of what their id is.

If you run the following piece of code, you’ll see that the two variables are not equal:

The reason for this is that instances detergentA and detergentB have different ids . In this case, we need to override the == operator and custom logic to determine equality.

Now that we know the different scenarios in which we define custom operators, let’s define our custom operator.

A custom operator is defined just like a function is defined in Swift. There are two types of operators you can define:

Global operator

  • Operator specific to a class/struct

The definition looks like the following:

There are different types of parameters you can define based on whether it is an infix or a prefix / postfix operator.

If it’s an infix operator, you can have two parameters, and, when it’s a prefix / postfix operator, you can have a single parameter.

With global operators, we first define the operator with the notation keyword ( infix , prefix or postfix ) and the operator keyword, like this:

Here’s an example:

Operator for class/struct

When we want to define an operator for a class or a struct, we need to define the operator function as a static function. The notation parameter is optional in case the operator is an infix operator (i.e., you have two parameters in the function signature), else you need to specify prefix or postfix :

Given that we’ve already looked at defining basic custom operators like + and == , let’s review some examples of how you can define custom compound operators or operators that mutate the parameters themselves.

We’ll do this by defining a custom compound arithmetic operator for the Velocity struct from earlier:

Now let’s execute the following statement:

Now, we’ll specify the notation of a custom operator.

In order to define the notation of a custom operator, you have three keywords for the corresponding notation:

When defining a global operator, you need to first define the operator’s notation, then define its functions. Note that this is not a compulsory step, but it’s necessary if you want to define global operators or hope to assign a precedence to it (which we’ll discuss in the next section).

Let’s look at the hypotenuse operator again, which is being defined as a global operator. You can see that we first define the operator with the notation and the symbol, then implement its logic:

When defining an operator for your own class/struct, you can directly use the notation keyword with the method definition. For example, let’s define a negation operator for Velocity as well, which negates both the xVelocity and yVelocity properties. This operator is going to be defined as a prefix operator:

You can also define the precedence of your operator using the precedence keywords, as mentioned in the precedence table above. This is usually done in the definition step:

This way, the compiler knows which operator needs to be executed first. In case no precedence is specified, it defaults to DefaultPrecedence , which is higher than TernaryPrecedence .

This brings us to the conclusion of what operators are in Swift and how you can create your own. Although they are pretty simple to use, understanding them is important because they are one of the most foundational constructs of any programming language.

You should be familiar with basic operators, as you will be using them frequently in your code, and, when it comes to custom operators, define them only if the symbol’s original meaning makes sense for you.

Get set up with LogRocket's modern error tracking in minutes:

  • Visit https://logrocket.com/signup/ to get an app ID

Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

swift assignment operator overloading

Stop guessing about your digital experience with LogRocket

Recent posts:.

JWT Authentication: Best Practices And When To Use It

JWT authentication: Best practices and when to use it

A guide for using JWT authentication to prevent basic security issues while understanding the shortcomings of JWTs.

swift assignment operator overloading

Auth.js adoption guide: Overview, examples, and alternatives

Auth.js makes adding authentication to web apps easier and more secure. Let’s discuss why you should use it in your projects.

swift assignment operator overloading

Lucia Auth: An Auth.js alternative for Next.js authentication

Compare Auth.js and Lucia Auth for Next.js authentication, exploring their features, session management differences, and design paradigms.

swift assignment operator overloading

Learn how to animate transitions in Angular apps

While animations may not always be the most exciting aspect for us developers, they’re essential to keep users engaged. In […]

swift assignment operator overloading

Leave a Reply Cancel reply

Coding Explorer Blog

Exploring how to code for iOS in Swift and Objective-C

Operator Overloading — Tailor Swift To Your Needs

Last updated on August 12, 2020

Sorry, but I have been waiting for months to make this pun.  So today, we are going to talk about Operator overloading in Swift.  This tool is very useful, but quite dangerous as well.  The “With great power comes great responsibility,” quote is very appropriate for operator overloading.  It can make your code a lot more concise, making even a function call seem like a 3-hour long lecture.  But with that, you can also make the code nigh-unreadable to anybody that is new to your code.

Be very careful with this tool, and use it where it make sense, such as how “adding” two Swift Strings together makes a new string with one string first, then the other afterwards.  You can make the addition operator print to the screen, make a network request, play music, or whatever else you could write a function for, but doing any of those would be a terrible idea in production code.  You should do only what is necessary for the operator and nothing else.  If you need different things like those, make an appropriately named function that makes it obvious that it will make a network request.

Whenever you think of whether to use operator overloading, you have to ponder whether it helps your code anymore than a simple function call.  The function call may be longer, but it is a whole lot more expressive as to what it does (if named appropriately).  If it looks like you are adding, subtracting, checking equality, or whatever else the built-in operators do though, and you do it enough in your code, Swift’s operator overloading may be the right tool for the job.

Operator Overloading

You should only use operator overloading in a way that is consistent with how the operator is normally used in Swift.  Here is an example I thought of that could make sense, though there are still some pitfalls with it.  Let’s say we want to find the amount of time between two Date objects.  It would make sense to get that via “laterDate – initialDate” right?  So let’s do that:

In this case, I chose the Calendar.Components of year, month, day, hour, minute, and second as the components to use in this subtraction.  Herein lies ones of the pitfalls.  There are several other Components I could choose.  If I just wanted to know the weeks between something, I could put that in instead for this.  Nonetheless, using these units give us what we would want in most calendrical calculations.  The next line just creates the DateComponents object using components:from:to: from the currentCalendar.  We’re taking advantage of the fact that a single line of code that returns something can be used without explicitly writing return, because it is pretty clear to the compiler that a function that returns a date components being the only thing called in a function that also returns DateComponents would simply want to forward that return.

An operator used between two values is called an  infix operator.  There are two other overloadable types of operators known as  prefix and  postfix , like the old ++i and i++ operators of yore.

As you can see from the top, this is just a function in Swift, but instead of a text name, we have a symbol as the name.  We specify the types of inputs for the left and right parts of the expression, and then specify the return type, which for this calculation should be an DateComponents object.  Now we can use it like this:

There was a bit of setup there, but most of it should be pretty easy to understand.  We first create an initial date, which has the value of the moment the Date object was created.  Then there’s an DateComponents object that has its year, month, and minute values set.  Then the laterDate constant is made, using Calendar’s dateByAddingComponents method, so that makes a value 1 year, 5 months, and 42 minutes in the future.  Then we actually test our new capability for the ” – ” operator.  When we look at the components of the result of our subtraction, you can see it has the correct value for the year, month, and minute value for exactly how far in the future it was.

I think that this function is a marginally okay use of operator overloading.  It is using the subtraction operator how it is normally used in math.  However, it hides several assumptions.  I already mentioned that it uses certain Calendar.Components, but not all of them.  Secondly, it uses Calendar’s current variable.  I think this makes sense, but it is nonetheless hidden.

If we just use the normal function call that is behind our overloaded operator, you can clearly see what calendar it is using and which flags you want.  That is why I only say that this is a marginally okay use of operator overloading.  It makes sense, but it hides those assumptions from the reader, making them have to look up the operator overloading function to see what assumptions are made.

The Equatable Protocol

There are a few places in Swift where operator overloading is actually encouraged.  If you want to be able to compare your custom class with the ” == ” operator, you will have to overload it.  If you are going to implement this, your class should probably adopt the Equatable protocol.  The Equatable protocol is used often with Generic functions (you can read more about them here:   Generic Functions in Swift ), when it will need to check for equality inside.  If you do, you only need to implement the ” == ” operator, you get the != for free (since it is basically just negating the ” == ” operator’s answer.

The way you overload the ” == ” operator is the same as with any other infix operator, like what we did above with the ” – ” operator.  Let’s make a custom type and overload the ” == ” operator below:

Now we can compare Temperature instances with the ” == ” operator.  When an operator is overloaded, it must be marked as static.  Actually, if I had made this a struct or enum, I wouldn’t even need the initializer or the operator overloading!  If the parts in it are hashable or equatable, structs and enums can generate those methods themselves, without me needing to explicitly write them.  The same is not extended to classes, and really, this type should’ve been a struct, but I wanted to show the behavior for a type that didn’t automatically get those methods when they adopt the protocol.

Another place where operator overloading in Swift is encouraged is with the Comparable protocol.  To conform to the Comparable protocol you must implement an operator function for the ” < ” operator, as well as conform to the Equatable protocol.  With you implementing == and > operators, the compiler can figure out the !=, <, <=, and >= operators for you.  You can see an example of this in my previous post Generic Functions in Swift .  It also has another example of overloading the ” == ” operator.

I debated showing the Date subtraction example above, due to how it hides many assumptions about the code being called.  I decided to share it though, because it also highlights what you have to think about when deciding to use operator overloading in Swift.  If you are doing subtraction of dates a lot in your code, always with the same unitFlags, overloading the subtraction operator could make your code a lot more readable.

There are a few operators that you cannot overload, most notably the assignment operator ” = ” (just one equal sign).  Even if you could, I’m not sure I would want to know the chaos that would be wrought by doing so, considering how much the assignment operator is used.  You can read more about the operators you can’t overload at  Tammo Freese ‘s article Facets of Swift, Part 5: Custom Operators .

Much like Custom Subscripts in Swift , this tool is very useful, but very dangerous.   Use it wisely .

In updating this post, there are two very welcome updates to Swift that made the code for the “-” operator’s overload much nicer.  Firstly, that you can use the most common Calendar.Components with their common names (.Year, .Month, etc.) instead of the longer original ones ( . YearCalendarUnit,  .Month CalendarUnit, etc.).  Secondly, the code used to use the OR operator ” | ” to combine the unit flags.  Now, Swift lets you give it a Swift Set type for options of that sort, which itself can be created with a Swift Array literal.

I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don’t hesitate to contact me on Twitter  @CodingExplorer , and I’ll see what I can do.  Thanks!

  • The Swift Programming Language – Apple Inc.
  • Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium
  • Terms Of Use
  • Privacy Policy
  • Affiliate Disclaimer

Subscribe to the Coding Explorer Newsletter

TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

 

Why does Swift need operator overloading?

Paul Hudson    @twostraws    May 28th 2020

Updated for Xcode 16

Operator overloading allows the same operator –  + , * , / , and so on – to do different things depending on what data you use it with. This allows us to use these symbols in various places where they would make sense: we can add two integers using +, we can append one string to another using +, we can join two arrays using +, and so on.

Of course, this doesn’t mean we can use all the operators in every place: we can subtract one integer from another, but what would it mean to subtract one string from another? Would it subtract from the start or the end? Would it subtract all instances of the string or just one?

When your skills grow you’ll find you can create your own custom operators if you want to, and even modify Swift’s existing operators.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until September 29th.

Click to save your spot

Sponsor Hacking with Swift and reach the world's largest Swift community!

Swift breaks down barriers between ideas and apps, and I want to break down barriers to learning it. I’m proud to make hundreds of tutorials that are free to access, and I’ll keep doing that whatever happens. But if that’s a mission that resonates with you, please support it by becoming a HWS+ member. It’ll bring you lots of benefits personally, but it also means you’ll directly help people all over the world to learn Swift by freeing me up to share more of my knowledge, passion, and experience for free! Become Hacking with Swift+ member.

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Link copied to your pasteboard.

Custom assignment operator

Currently, swift's = operator does not return a value. This seems like a lapse to me, because, if it was othersise, then some usage in function builder would be simpler. But that's okay, since there is the ability to declare a custom one. Right?

But it produces a bunch of errors, from one suggesting that it is incorrectly used prefix unary func to the other saying to separate statements. All of this obviously indicates that I cannot properly work with lvalues. Can I?

That syntactic position cannot take an arbitrary operator. But more importantly, the operation done by var someView = expression is initialization, not assignment — so even if an arbitrary operator were allowed in that position, what you're trying to do wouldn't be allowed, because it's not okay to bind an inout parameter to an uninitialized variable.

It's also not clear why

aren't both better solutions than introducing a new operator.

To be able to reference objects by name in fb closure, rather than putting there ugly stuff, like a bunch of explicit returns. Currently, you have to ...

If I could make a custom assignment, then that would become

Nice and clean, which is the whole point of this function building stuff, no?

Why so? If there were such thing in swift as customizable assignment operator, then it would be not important if lvalue was initialized, because that what custom = would do.

There are much more applications to a custom assignment. What I have shown is the one among those missed opportunities for clean code simply because of yet another language limit.

What is point than to have a assignment field/property in precedence group declaration?

Please don't tell me that it is there because swift cannot deterministically resolve operators based on argument mutability

Leads to Ambiguous use of operator '=>

The problem with accepting uninitialized value for inout argument is that the function can READ inout arguments. The function signature says nothing about only writing to the said inout variable.

Mostly because, while being special, = is still an operator. It still needs to interact with other operators when parsing. Also, = is not the only operators of this class, *= and -= are normal operators that have AssignmentPrecedence .

It is to make assignment operators work “inside” of optional chaining:

It could be made such that operators with assignment wouldn't be able to read the value. Problem solved?

It might be better to propose implementing an out parameter which could take uninitialised variables. This could be somewhat useful in other situations like factoring out parts of initialisers. I'm not sure it's useful enough to be implemented, because it's not commonly needed and you can always just return the values instead and move the variables to the LHS, but it would be better than making a weird special case.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Alternative to overloading the assignment operator in Swift

I'm making a String struct (called ScalarString ) from scratch that internally is an array of UInt32 Unicode scalar values (see this question for background).

For a normal Swift String I can do the following:

I would like to do

where I overload the assignment operator to convert the "hello" String automatically to ScalarString behind the scenes. However, this SO Q&A tells me that is not possible.

I could write a method like

but that isn't as readable as the assignment operator. Is there any alternative?

  • operator-overloading

Community's user avatar

To make an assignment

work with a string literal on the right-hand side, it suffices that you implement the StringLiteralConvertible for your type:

However, this works only for string literals, not for arbitrary strings, so this would not compile:

because (as you already noticed) you cannot overload the assignment operator, and you would have to use your init method explicitly:

In the same manner, you could create a value of your type from a literal array of Unicode values

by implementing the ArrayLiteralConvertible protocol:

Martin R's user avatar

  • So this allows one to make an assignment to a string (or array) literal (not a variable) during initialization only, correct? That is, I couldn't do something like let myString = ScalarString() to initialize an empty string and then later set the value with myString = "hello" . –  Suragch Commented Jul 22, 2015 at 2:15
  • And if my statement above is correct, what is the special magic that Swift does to give this functionality to its own String struct? –  Suragch Commented Jul 22, 2015 at 2:18
  • @Suragch: var myString = ScalarString() ; ... ; myString = "hello" should be possible with the above extensions. – The Swift compiler can do many things that we cannot to (e.g. automatic conversion of Int, Double, String etc to NSObject if necessary). –  Martin R Commented Jul 22, 2015 at 5:28

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged string swift operator-overloading or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Connections vertically and horizontally
  • Basic question - will "universal" SMPS work at any voltage in the range, even DC?
  • Doesn't nonlocality follow from nonrealism in the EPR thought experiment and Bell tests?
  • Is a thing just a class with only one member?
  • How can I verify integrity of the document types?
  • Analog of Birkhoff's HSP theorem regarding ultraproducts and elementary sublattices
  • "Tail -f" on symlink that points to a file on another drive has interval stops, but not when tailing the original file
  • Why would the GPL be viral, while EUPL isn't, according to the EUPL authors?
  • Movie where a young director's student film gets made (badly) by a major studio
  • NSolve uses all CPU resources
  • Help updating 34 year old document to run with modern LaTeX
  • O(nloglogn) Sorting Algorithm?
  • The consequence of a good letter of recommendation when things do not work out
  • grouping for stdout
  • How do elected politicians get away with not giving straight answers?
  • How can I support a closet rod where there's no shelf?
  • What are the pros and cons of the classic portfolio by Wealthfront?
  • Is Produce Flame a spell that the caster casts upon themself?
  • What would the natural diet of Bigfoot be?
  • Trying to match building(s) to lot(s) when data has margin of error in QGIS
  • How can a D-lock be bent inward by a thief?
  • Why Pythagorean theorem is all about 2?
  • What would be an appropriate translation of Solitude?
  • Concerns with newly installed floor tile

swift assignment operator overloading

COMMENTS

  1. how to overload an assignment operator in swift

    It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded. If that doesn't convince you, just change the operator to +=: func +=(left: inout CGFloat, right: Float) {. left += CGFloat(right) }

  2. How to create custom operators and do operators overloading in Swift

    Not every type of operator can be overload. There are four restrictions that I know of: You can't overload and create a custom ternary operator. You can't overload the default assignment operator (=). You can overload other binary operators, including compound assignment operators such as a += 2. Only a subset of the ASCII characters are supported.

  3. Overloading & Creating New Operators In Swift 5

    Overloading & Creating New Operators In Swift 5. We'll cover everything you need to know about operator overloading and creating custom operators with unique precedence and associativity behavior. Operator overloading allows you to change how existing operators (e.g. +, -, *, /, etc.) interact with custom types in your codebase.

  4. Advanced Operators

    Bitwise XOR Operator. The bitwise XOR operator, or "exclusive OR operator" (^), compares the bits of two numbers.The operator returns a new number whose bits are set to 1 where the input bits are different and are set to 0 where the input bits are the same:. In the example below, the values of first Bits and other Bits each have a bit set to 1 in a location that the other does not.

  5. Operator Overloading in Swift Tutorial

    Enter the following in your playground to confirm Swift operators follow these same rules: var sumWithMultiplication = 1 + 3 - 3 * 2. You'll see the following result: -2. In cases where arithmetic operators have the same precedence, Swift evaluates the operators from left to right.

  6. How do you overload an operator in swift?

    Basically, I'm looking to overload the "+" operator so that it knows which "version" of the "+" to use depending of the type. swift; operator-overloading; operators; ... how to overload an assignment operator in swift. 1. Declare overloaded += operator as mutating? 2. Swift ambiguous overloaded + operator.

  7. A Comprehensive Guide to Swift Operator Overloading

    The overloading operators must be marked with the static keyword and can be defined within class, struct, or enum types to perform operations that involve their instances. Swift provides a comprehensive set of operators, which are categorized as unary, binary, and ternary: • Unary operators operate on a single target.

  8. How to use operator overloading

    Operator overloading is the practice of adding new operators and modifying existing ones to do different things. Operators are those little symbols like +, *, and /, and Swift uses them in a variety of ways depending on context - a string plus another string equals a combined string, for example, whereas an integer plus another integer equals a summed integer.

  9. Operator overloading

    Operator overloading. Swift supports operator overloading, which is a fancy way of saying that what an operator does depends on the values you use it with. For example, + sums integers like this: let meaningOfLife = 42 let doubleMeaning = 42 + 42. But + also joins strings, like this:

  10. Operator Overloading in Swift

    In Swift, operator overloading provides a powerful mechanism for extending the functionality of built-in operators to work with custom types. By defining custom implementations for operators like +, -, *, and more, developers can imbue their own types with expressive and intuitive behavior, enhancing code readability and maintainability. In this guide, we'll

  11. Overloading Custom Operators in Swift

    Swift operators are particularly powerful because you can alter them to suit your needs in two ways: assigning new functionality to existing operators (known as operator overloading), and creating new custom operators. Throughout this tutorial, you'll use a simple Vector struct and build your own set of operators to help compose different ...

  12. Overloading assignment operator

    Overloading assignment operator. Evolution Discussion. Don_Wills (Don Wills) December 6, 2015, 1:44pm 1. The ability to overload operators is very useful. However, that utility is diminished without the ability to overload the simple assignment operator ( = ). I vaguely recall reading somewhere that there is a reason for this having to do with ...

  13. Compound assignment operators

    Swift has shorthand operators that combine one operator with an assignment, so you can change a variable in place. These look like the existing operators you know - +, -, *, and /, but they have an = on the end because they assign the result back to whatever variable you were using. For example, if someone scored 95 in an exam but needs to be ...

  14. Creating custom operators in Swift

    The most common operators that Swift ships with fall under the following categories: 1. Assignment operator. Assignment operators are used to assign values to a constant or variable. The symbol is =. 2. Arithmetic operators. These operators are used to perform basic arithmetic operations, such as +, -, *, /, and %. 3. Logical operators

  15. Operator Overloading

    Another place where operator overloading in Swift is encouraged is with the Comparable protocol. To conform to the Comparable protocol you must implement an operator function for the " < " operator, as well as conform to the Equatable protocol. ... There are a few operators that you cannot overload, most notably the assignment operator ...

  16. Why does Swift need operator overloading?

    Updated for Xcode 16. Operator overloading allows the same operator - +, *, /, and so on - to do different things depending on what data you use it with. This allows us to use these symbols in various places where they would make sense: we can add two integers using +, we can append one string to another using +, we can join two arrays ...

  17. Custom assignment operator

    That syntactic position cannot take an arbitrary operator. But more importantly, the operation done by var someView = expression is initialization, not assignment — so even if an arbitrary operator were allowed in that position, what you're trying to do wouldn't be allowed, because it's not okay to bind an inout parameter to an uninitialized variable.

  18. How can I get access or overridden the = operator in Swift?

    There is possibility in Swift for defining new custom operators like infix operator ** but I do not want define a new operator, I want get access to the function or logic of = in Swift. Here is what I am think about = operator, this code is just for show case and it does not work. infix operator =. func =<T>(rhs: T) {. // My custom code is here:

  19. Alternative to overloading the assignment operator in Swift

    For a normal Swift String I can do the following: let myString: String = "hello" I would like to do . let myScalarString: ScalarString = "hello" where I overload the assignment operator to convert the "hello" String automatically to ScalarString behind the scenes. However, this SO Q&A tells me that is not possible.