Swift Tutorial

  • Swift Tutorial
  • Swift - Home
  • Swift - Overview
  • Swift - Environment
  • Swift - Basic Syntax
  • Swift - Variables
  • Swift - Constants
  • Swift - Literals
  • Swift - Comments
  • Swift Operators
  • Swift - Operators
  • Swift - Arithmetic Operators
  • Swift - Comparison Operators
  • Swift - Logical Operators

Swift - Assignment Operators

  • Swift - Bitwise Operators
  • Swift - Misc Operators
  • Swift Advanced Operators
  • Swift - Operator Overloading
  • Swift Customized Operators
  • Swift - Advanced Operators
  • Swift - Arithmetic Overflow Operators
  • Swift - Identity Operators
  • Swift - Range Operators
  • Swift Data Types
  • Swift - Data Types
  • Swift - Integers
  • Swift - Floating-Point Numbers
  • Swift - Double
  • Swift - Boolean
  • Swift - Strings
  • Swift - Characters
  • Swift - Type Aliases
  • Swift - Optionals
  • Swift - Tuples
  • Swift - Assertions and Precondition
  • Swift Control Flow
  • Swift - Decision Making
  • Swift - if statement
  • Swift - if...else if...else Statement
  • Swift - if-else Statement
  • Swift - nested if statements
  • Swift - switch statement
  • Swift - Loops
  • Swift - for in loop
  • Swift - While loop
  • Swift - repeat...while loop
  • Swift - continue statement
  • Swift - break statement
  • Swift - fall through statement
  • Swift Collections
  • Swift - Arrays
  • Swift - Sets
  • Swift - Dictionaries
  • Swift Functions
  • Swift - Functions
  • Swift - Nested Functions
  • Swift - Function Overloading
  • Swift - Recursion
  • Swift - Higher-Order Functions
  • Swift Closures
  • Swift - Closures
  • Swift-Escaping and Non-escaping closure
  • Swift - Auto Closures
  • Swift - Enumerations
  • Swift - Structures
  • Swift - Classes
  • Swift - Properties
  • Swift - Methods
  • Swift - Subscripts
  • Swift - Inheritance
  • Swift-Overriding
  • Swift - Initialization
  • Swift - Deinitialization
  • Swift Advanced
  • Swift - ARC Overview
  • Swift - Optional Chaining
  • Swift - Error handling
  • Swift - Concurrency
  • Swift - Type Casting
  • Swift - Nested Types
  • Swift - Extensions
  • Swift - Protocols
  • Swift - Generics
  • Swift - Access Control
  • Swift Miscellaneous
  • Swift - Function vs Method
  • Swift - SwiftyJSON
  • Swift - Singleton class
  • Swift Random Numbers
  • Swift Opaque and Boxed Type
  • Swift Useful Resources
  • Swift - Compile Online
  • Swift - Quick Guide
  • Swift - Useful Resources
  • Swift - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators are the special operators. They are used to assign or update values to a variable or constant. In the assignment operators, the right-hand side of the assignment operator is the value and the left-hand side of the assignment operator should be the variable to which the value will be assigned.

The data type of both sides should be the same, if they are different we will get an error. The associativity of assignment operators is from right to left. Swift supports two types of assignment operators −

Simple Assignment Operator − It is the most commonly used operator in Swift. It is used to assign value to a variable or constant.

Compound Assignment Operators − They are the combination of assignment operator (=) with other operators like +, *, /, etc.

The following table shows all the assignment operators supported by Swift −

Operators Name Example
(=) Assignment var x = 10
+= Add and Assignment A += B is equivalent to A = A + B
-= Subtract and Assignment A -= B is equivalent to A = A - B
*= Multiply and Assignment A *= B is equivalent to A = A * B
/= Divide and Assignment A /= B is equivalent to A = A / B
%= Modulo and Assignment A %= B is equivalent to A = A % B
&= Bitwise AND and Assignment A &= B is equivalent to A = A & B
|= Bitwise Inclusive OR and Assignment A += B is equivalent to A = A | B
^= Bitwise Exclusive OR and Assignment A ^= B is equivalent to A = A ^B
<<= Left Shift and Assignment A <<= B is equivalent to A = A << B
>>= Right Shift and Assignment A >>= B is equivalent to A = A >> B

Assignment Operator in Swift

An assignment operator "=" is the most straightforward and commonly used operator in Swift. It is used to assign value to a constant or variable. The left-hand side of the assignment operator contains the variable name and the right-hand side contains the value.

While using the assignment operator always remember the data type of both the operands should be the same.

Following is the syntax of the assignment operator −

Swift program to assign a string to a variable.

Add and Assignment Operator in Swift

An Add and Assignment Operator "+=" is used to perform addition between the left variable and right variable and then assign the result to the left variable. Suppose we have two variables A = 10 and B = 20. A += B => A = 10 + 20 => A = 30.

Following is the syntax of the add and assignment operator −

Swift program to find the sum of two variables using add and assignment operator "+=".

Subtract and Assignment Operator in Swift

A Subtract and Assignment Operator "-=" is used to perform a subtraction between the left variable and the right variable and then assign the result to the left variable. Suppose we have two variables A = 10 and B = 20. A -= B => A = 10 - 20 => A = -10.

Following is the syntax of the subtract and assignment operator −

Swift program to subtract two variables using subtract and assignment operator "-=".

Multiply and Assignment Operator in Swift

A Multiply and Assignment Operator "*=" is used to perform a multiplication between the left operand and the right operand and then assign the result to the left operand. Suppose we have two variables A = 10 and B = 20. A *= B => A = 10 * 20 => A = 200.

Following is the syntax of the multiply and assignment operator −

Swift program to find the product of two variables using multiply and assignment operator "*=".

Divide and Assignment Operator in Swift

A Divide and Assignment Operator "/=" is used to divide the left operand by the right operand and then assign the result to the left operand. Suppose we have two variables A = 20 and B = 5. A /= B => A = 20 / 5 => A = 4.

Following is the syntax of the divide and assignment operator −

Swift program to find the divide two variables using divide and assignment operator "/=".

Modulo and Assignment Operator in Swift

A Modulo and Assignment Operator "%=" is used to calculate the modulus or remainder of two operands and assign the result to the left operand. For example, we have two variables A = 20 and B = 5. A %= B => A = 20 & 5 => A = 0.

Following is the syntax of the modulo and assignment operator −

Swift program to find the modulus of two variables using modulo and assignment operator "%=".

Bitwise AND and Assignment Operator in Swift

A Bitwise AND and Assignment Operator "%=" is used to perform AND operation between two variables or operands and assign the final result to the left variable. For example, we have two variables A = 9 and B = 10. A &= B => A = 9 & 10 => A = 8.

Following is the syntax of the bitwise AND and assignment operator −

Swift program to bitwise AND in between two variables using bitwise AND and assignment operator "&=".

Bitwise Inclusive OR and Assignment Operator in Swift

A Bitwise Inclusive OR and Assignment Operator "^=" is used to perform OR operation between two variables or operands and assign the final result to the left-hand side variable.

For example, we have two variables A = 9 and B = 10. A ^= B => A = 9 ^ 10 => A = 3.

Following is the syntax of the bitwise inclusive OR and assignment operator −

Swift program to bitwise OR in between two variables using bitwise OR and assignment operator "^=".

Bitwise Exclusive OR and Assignment Operator in Swift

A Bitwise Exclusive OR and Assignment Operator "|=" is used to perform exclusive OR operation between two variables or operands and assign the final result to the left-hand side variable.

For example, we have two variables A = 10 and B = 10. A |= B => A = 9 | 10 => A = 10.

Following is the syntax of the bitwise exclusive OR and assignment operator –

Swift program to bitwise OR in between two variables using bitwise OR and assignment operator "|=".

Left Shift and Assignment Operator in Swift

A Left Shift and Assignment Operator "<<=" is used to shift the bits of the given operand on the left side according to the given positions and assign the final result to the left-hand side variable.

Following is the syntax of the left shift and assignment operator −

Swift program to shift the bits of the given value on the left side using the left shift and assignment operator "<<=".

Right Shift and Assignment Operator in Swift

A Right Shift and Assignment Operator ">>=" is used to shift the bits of the given operand on the right side according to the given positions and assign the final result to the left-hand side variable.

Following is the syntax of the right shift and assignment operator −

Swift program to shift the bits of the given value on the right side by 4 positions using the right shift and assignment operator ">>=".

To Continue Learning Please Login

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
  • Screen Library
  • 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

Inside Swift Operators: Your Guide to Effortless Coding with Swift

Authore Name

Parth Asodariya

Detail Image

Frequently asked questions

What is a swift operator, what is the precedence of operators in swift, how to use logical operators in swift, what is an example of a range operator in swift, is there operator overloading in swift.

Swift, Apple's powerful and intuitive programming language, has been a game-changer since its introduction. It simplifies the complexities of app development, making it accessible to a broader audience.

A fundamental aspect of Swift—and any programming language—is its operators. Operators in Swift perform various tasks, from basic arithmetic to logical comparisons and more.

In this blog, we will understand Swift operators, and how they impact your code, and cover everything from arithmetic to custom operators. Being fluent with operators is helpful to understand the grammar of a language—it allows you to write clearer, more efficient code and is essential for any developer looking to master Swift.

Basic Swift Operators

Operators are special symbols used within Swift to execute particular operations on values and variables—known as operands. They can manipulate number values, string values, boolean values, and other data types by performing tasks such as assignments, arithmetic calculations, comparisons, or logic.

Exploring Arithmetic Operators in Swift

Arithmetic operators are the most familiar operators, performing mathematical operations on numerical values. These include the addition (+), subtraction (-), multiplication (*), division (/), and remainder (%) operators. Arithmetic operators in Swift are used in the same way as in mathematics.

In the above example, sum, difference, product, and quotient all hold the final value after the respective operation is applied to two values. The remainder operator % provides the remainder of the division, signifying operations are not merely limited to elementary arithmetic but also accommodate modular arithmetic in Swift.

Usage of Arithmetic Operators With Examples

The ability to print consistent and accurate arithmetic operations remains a building block of Swift applications. For instance, a currency converter app performs arithmetic operations to determine exchange rates. Consider the following example:

The code sample uses an arithmetic operator to calculate a currency conversion from dollars to euros and outputs the result with the print function.

Logical Operators in Swift

Swift logical operators evaluate boolean value expressions, allowing code to make decisions. Logical operators include && (logical AND), || (logical OR), and ! (logical NOT). Here's a brief look at how these Swift logical operators control program flow:

• && returns true if both expressions are true.

• || returns true if at least one of the expressions is true.

• ! inverts the boolean value of an expression.

In the example, the front-page feature requirement depends on both having a high score and good reviews. The use of && ensures that both conditions must be met for the conditional branch to execute.

Swift Operator Overloading

Swift operator overloading allows developers to provide a custom implementation of existing operators for their types or create new operators with customized behavior. This feature is particularly powerful as it enables clean and intuitive usage of custom types, akin to Swift’s built-in types.

To overload an operator, you define a new implementation using the func keyword and specifying the operator's symbols:

Overloading the + operator allows adding two Vector2D instances, returning a new Vector2D that represents the sum of the original vectors.

Operators for Swift Ranges

A range in Swift represents a sequence of consecutive values, which can be numbers, characters, or another sequence type. Using range operators is essential when working with arrays, loops, or any context where you need to specify a span of values.

The Closed Range Operator

The closed range operator (...) includes all the values within the range, extending from the lower bound to the upper bound. This operator is extremely useful when you want to iterate over all the elements in a collection without excluding any.

Here's an example of a closed range in action:

In the above code, the loop iterates over a closed range that includes the numbers 1 through 5.

The Half-Open Range Operator

Conversely, the half-open range operator (..<) includes values from the lower bound up to, but not including, the upper bound value. The half-open range is especially useful when working with zero-based lists like arrays, where you wish to include all the elements up to the one before the last.

Consider this example using a half-open range:

Here we access the array index using the half-open range to access all the elements within the fruits array without exceeding its bounds.

Swift Range Operator Applications

Ranges in Swift are powerful tools that simplify code involving sequences of values. Whether for use in a loop to iterate over a set number of iterations or to slice off subsets from collections, range operators help streamline these operations.

Let's see how range operators manage swift ranges through a collection slicing example:

The example demonstrates the closed range operator by slicing an array to create a new passingScores array containing elements at indices 1 to 3 from the scores array.

Advanced Swift Operators

Beyond the basics, Swift provides a suite of advanced operators that perform more complex operations. These include bitwise operators for manipulating binary data, and compound assignment operators (such as += and *=) that combine assignment (=) with another operation.

Let's explore the bitwise and assignment operator used in Swift:

Bitwise Operators in Swift

Bitwise operators allow operations on individual bits of integers. They are used when performing low-level programming, such as graphics programming or device driver creation.

For example, the bitwise AND operator (&) compares the bits of two integers and returns a new integer with bits set to 1 only where both original integers had them at 1:

Compound Assignment Operators

Compound assignment operators provide a shorthand way to modify the value of variables. For instance, instead of writing x = x + 2, you can simply write x += 2.

In the above code, we first defined a score variable, and then used a compound assignment operator to subtract 5 from the current value of the score.

Swift Operator Precedence and Associativity

Understanding operator precedence and associativity is crucial in Swift, as it determines the order in which operations are executed. The operator's precedence gives some operations higher priority than others, whereas associativity defines the order operations of the same precedence are performed.

For example, the multiplication operator (*) has a higher precedence than the addition operator (+). Therefore, the multiplication is performed before addition in a non-parenthesized expression.

In Swift, operators with the same precedence level are evaluated according to their associativity. Most arithmetic operators are left associative, meaning they evaluate from left to right.

Custom Operators and Precedence

Swift allows you to define your operator with custom precedence and associativity. To create a new operator, use the operator keyword, and then specify the precedence group to dictate how it interacts with other operators.

In this example, a custom infix operator named ^^ is defined for exponentiation, with precedence higher than multiplication and right associativity.

In this post, we've taken an extensive look into Swift operators, solidifying them as indispensable tools in a developer's toolkit. From handling arithmetic calculations to manipulating swift ranges and customizing behavior through operator overloading, operators in Swift are versatile and powerful.

Recognizing the significance of operators in Swift will not only streamline your coding process but also open up a world of possibilities for creating efficient and readable code. As you continue on your journey with Swift, let the mastery of operators empower your development, enabling you to craft elegant solutions with precision and ease.

Keep practicing, and explore new ways to leverage operators in your projects, and soon you'll be using them to their full potential, just as effortlessly as you write a print statement. Happy coding!

Basic Operators

Christine_Yang's avatar

Basic operators in Swift are commonly used to evaluate, reassign, and combine values.

Assignment Operator

The assignment operator = in Swift is the same as in most other languages and serves the same purpose. It is used to initialize or reassign a variable to some value. In Swift, unlike some other high-level programming languages like C or Java, the assignment operator does not return any values.

Here, the z = (a=6) assignment leaves z to equal () once the a=6 is evaluated.

Arithmetic Operators

Swift contains the following operators that match their similar expressions in common math:

  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulus/remainder division: a % b

These work as expected for all mathematical operations, however, the + operator can also be used to concatenate two strings together such as "Operators" + " in Swift" = "Operators in Swift" .

Comparison Operators

These operators are used to return Bool values for use in conditional statements. These control logic flow in loops or if statements for example. The basic comparison operators are below:

  • Equal to: this == that
  • Not equal to: this != that
  • Greater than: this > that
  • Greater than or equal to: this >= that
  • Less than: this < that
  • Less than or equal to: this <= that

The following code snippet shows a use case of comparison operators in a while loop:

Logical Operators

Logical operators are used to evaluate or modify the value of Boolean values and are especially useful in control flow logic. In Swift, there are three operators:

  • Logical NOT: !this
  • Logical AND: this && that
  • Logical OR: this || that

Logical NOT ( ! ) operator appears directly before a Boolean value with no spaces. This operator inverts the value of the Boolean so that true becomes false and vice versa.

The logical AND ( && ) and OR ( || ) operators evaluate two Boolean values or expressions. In an AND evaluation, both expressions must result in true , resulting in the overall AND expression becoming true . In an OR evaluation only one expression must be true for the result of OR to be true . In both cases, if the left side of the expression evaluates to a value that the compiler can determine a value for the operator, the right side will not be evaluated at all.

Range Operators

Range operators provide quick and convenient ways of creating various ranges or iterating over elements in an object. The three primary types are Closed ( a...z ), Half-Open ( a..<z ), and One-Sided ( a... ), each providing different limits on the range. Swift does not allow for the creation of decrementing ranges, therefore the value of the first variable must not be greater than the value of the second.

The Closed Range operator ( a...z ) creates a range that begins at a and continues to and includes, z . The most common use case for Closed Range Operators is in for-in loops.

This should output:

Half-Open range operators ( a..<z ) create a range beginning at a and continue to z but not including z . They are commonly used when working with arrays or other zero-indexed lists.

The One-Sided range operator defines a range that will continue as far in one direction as possible. We can use this range to iterate from or to specific ranges inside of other fixed-length entities.

Nil-Coalescing Operator

The nil-coalescing operator ( a ?? z ) unwraps an optional with the value of a unless a is nil , then it will return the value of z . a always has to be an optional type and z has to match the type that’s stored in a .

Since getItemPrice isn’t assigned a value it defaults to 'nil' . The price to charge the customer is either a price we get from an item or the default price. In this case, priceToChargeCustomer = 1.99

Ternary Conditional Operator

The ternary conditional operator is shorthand for an if - else statement.

  • If the statement is true , the code on the left side of the ternary evaluates and returns a value.
  • If it is false , the right side of the ternary evaluates and returns a value.

This would output:

All contributors

  • Christine_Yang

Looking to contribute?

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn Swift on Codecademy

Build ios apps with swiftui, learn swift.

WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

 

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 penalized 5 points, you could write this:

Similarly, you can add one string to another using += :

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price , so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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: 4.8/5

Unknown user

You are not logged in

Link copied to your pasteboard.

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

what is assignment operator in swift

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.

what is assignment operator in swift

Over 200k developers use LogRocket to create better digital experiences

what is assignment operator 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

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)

what is assignment operator in swift

Stop guessing about your digital experience with LogRocket

Recent posts:.

Signals Vs Ngonchanges For Better Angular State Management

Signals vs. ngOnChanges for better Angular state management

Angular is evolving in some exciting ways. Explore how signals enhance state management compared to the “old” approach using ngOnChanges .

what is assignment operator in swift

An advanced guide to Vitest testing and mocking

Use Vitest to write tests with practical examples and strategies, covering setting up workflows, mocking, and advanced testing techniques.

what is assignment operator in swift

Optimizing rendering in Vue

This guide covers methods for enhancing rendering speed in Vue.js apps using functions and techniques like `v-once`, `v-for`, `v-if`, and `v-show`.

what is assignment operator in swift

Using Google Magika to build an AI-powered file type detector

Magika offers extremely accurate file type identification, using deep learning to address the limitations of traditional methods.

what is assignment operator in swift

Leave a Reply Cancel reply

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Swift Tutorial

Swift Introduction

  • Swift - Hello World Program
  • Swift - Basic Syntax
  • Swift - Keywords
  • Swift - Literals
  • Swift - Constants, Variables & Print function
  • Swift - Operators

Swift Data Types

  • Swift - Data Types
  • Swift - Integer, Floating-Point Numbers
  • Strings in Swift
  • String Functions and Operators in Swift
  • How to Concatenate Strings in Swift?
  • How to Append a String to Another String in Swift?
  • How to Insert a Character in String at Specific Index in Swift?
  • How to check if a string contains another string in Swift?
  • How to remove a specific character from a string in Swift?
  • Data Type Conversions in Swift
  • Swift - Convert String to Int Swift

Swift Control Flow

  • Swift - Decision Making Statements
  • Swift - If Statement
  • Swift - If-else Statement
  • Swift - If-else-if Statement
  • Swift - Nested if-else Statement
  • Swift - Switch Statement
  • Swift - Loops
  • Swift - While Loop
  • Swift - Repeat While loop
  • Swift - For-in Loop
  • Swift - Control Statements in Loops
  • Swift - Break Statement
  • Swift - Fallthrough Statement
  • Swift - Guard Statement

Swift Functions

  • Calling Functions in Swift
  • Swift Function Parameters and Return Values
  • How to Use Variadic Parameters in Swift?
  • Swift - In Out Parameters
  • Swift - Nested Function
  • Swift - Function Overloading
  • Closures in Swift
  • Escaping and Non-Escaping Closures in Swift
  • Higher-Order Functions in Swift

Swift Collections

  • Swift - Arrays
  • Swift - Arrays Properties
  • Swift - How to Store Values in Arrays?
  • How to Remove the last element from an Array in Swift?
  • How to Remove the First element from an Array in Swift?
  • How to count the elements of an Array in Swift?
  • How to Reverse an Array in Swift?
  • Swift Array joined() function
  • How to check if the array contains a given element in Swift?
  • Sorting an Array in Swift
  • How to Swap Array items in Swift?
  • How to check if an array is empty in Swift?
  • Swift - Sets
  • Swift - Set Operations
  • How to remove first element from the Set in Swift?
  • How to remove all the elements from the Set in Swift?
  • How to check if the set contains a given element in Swift?
  • How to count the elements of a Set in Swift?
  • Sorting a Set in Swift
  • How to check if a set is empty in Swift?
  • How to shuffle the elements of a set in Swift?
  • Swift - Difference Between Sets and Arrays
  • Swift - Dictionary
  • Swift - Tuples
  • Swift - Iterate Arrays and Dictionaries
  • Swift Structures
  • Swift - Properties and its Different Types
  • Swift - Methods
  • Swift - Difference Between Function and Method
  • Swift - Deinitialization and How its Works?
  • Typecasting in Swift
  • Repeating Timers in Swift
  • Non Repeating Timers in Swift
  • Difference between Repeating and Non-Repeating timers in Swift
  • Optional Chaining in Swift
  • Singleton Class in Swift

Swift Additional Topics

  • Swift - Error Handling
  • Difference between Try, Try?, and Try! in Swift
  • Swift - Typealias
  • Important Points to Know About Java and Swift
  • Difference between Swift Structures and C Structure
  • How to Build and Publish SCADE Apps to Apple and Google Stores?
  • 6 Best iOS Project Ideas For Beginners

Swift – Operators

Swift is a general-purpose, multi-paradigm, and compiled programming language which is developed by Apple Inc. In Swift, an operator is a symbol that tells the compiler to perform the manipulations in the given expression. Just like other programming languages, the working of operators in Swift is also the same. We can perform multiple operations using operators in our programs there are multiple operators available in Swift. In this article, we will learn all types of operators which are present in the Swift programming language.

Arithmetic Operators

  • + (Addition): This operator is used to add two variables.
  • – (Subtraction): This operator is used to subtract the second variable from the first.
  • / (Division): This operator is used to divide the first variable from the second.
  • * (Multiplication): This operator is used to multiply the first variable with the second.
  • % (Modulus): This operator gives the remainder after division first from second.

Assignment Operators

  • = (Equal): This operator is used to assign values from the right side variable to the left side variable.
  • += (Plus equal to): This operator is used to add the right variable to the left variable and assign the result to the left variable.
  • -= (Minus equal to): This operator is used to subtract the right variable from the left variable and assign the result to the left variable.
  • /= (Divide equal to): This operator is used to divide the left variable with the left variable and assigns the result to the left variable.
  • *= (Multiply equal to): This operator is used to multiply the right variable with the left variable and assign the result to the left variable.
  • %= (Modulus equal to): This operator is used to take modulus using two variables and assigns the result to the left variable

Bitwise Operators

  • << (Left Shift): The left variable value is moved left by the number of bits mentioned by the right variable.
  • >> (Right Shift): The left variable value is moved right by the number of bits mentioned by the right variable.
  • & (Binary AND): This operator copies bits to the result if the bits are set in both variables.
  • | (Binary OR): This operator copies bits to the result if the bits are set in any variables.
  • ^ (Binary XOR): This operator copies bits to the result if the bits are set on only one variable.
  • ~ (Tilde): This operator gives binary one’s complement of the variable

Comparison Operators

  • < (Less than): If the value of the left variable is less than the value of the right variable then the condition becomes true.
  • > (Greater than): If the value of the left variable is greater than the value of the right variable then the condition becomes true.
  • == (Equal to equal to): If the value of both variables is equal then the condition becomes true.
  • <= (Less than Equal to): If the value of the left variable is less than or equal to the value of the right variable then the condition becomes true.
  • >= (Greater than Equal to): If the value of the left variable is greater than or equal to the value of the right variable then the condition becomes true.
  • != (Not equal to): If the value of both variables is not equal then the condition becomes true.

Logical Operators

  • && (Logical AND): If both the side conditions are true, then the condition becomes true.
  • || (Logical OR): If any side condition is true, then the condition becomes true.
  • ! (Logical NOT): T his operator is to reverse the logical state.

Misc Operators

  • Cond ? A : B (Ternary Operator): If the condition becomes true, then value A will be assigned otherwise the value B will be assigned.
  • (A ?? B) (Nil-coalescing Operator): If the user didn’t pass any value to the variable then the default value will be nil.
  • ++ (Increment): This operator has been used to increase the value of the variable by 1.
  • — (Decrement): This operator is used to decrease the value of the variable by 1.

Range Operators

  • (a…b) (Closed Range Operator) — It runs from a to b including the values a and b. It is used in mostly used in for-in loops.
  • (a..<b) ( Half-Open Range Operator) — It runs from a to b, but it doesn’t include the value of b. It is used in mostly used in for-in loops.
  • [a…] (One-Sided Range Operator) — It will run for ranges that continue as far as possible in one direction.

Operator Precedence

In swift operator, precedence is used to find the grouping terms in the given expression. Also, used to evaluate the expression. For example, y = 3 + 4 * 2, here * has the highest precedence so first, we solve 4 *2 and then we add the result with 3. Precedence will decrease while we visit the bottom of the table given below.

Operator Name Operators
Bitwise Shift <<, >>
Multiplicative %, *, /
Additive |, -, +, -, ^
Range Operators ..<, …
Nil-Coalescing Operator ??
Comparison Operators <, >, <=. >=, ==, !=
Logical Operators &&, ||
Ternary Operator ? :
Assignment Operators |=, %=, /=, *=, >>=, <<=, ^=, +=, -=

author

Please Login to comment...

Similar reads.

  • Swift-Basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

SwiftLee

A weekly blog about Swift, iOS and Xcode Tips and Tricks

Every Tuesday, curated Swift content from the community for free.

Give your simulator superpowers

RocketSim: An Essential Developer Tool as recommended by Apple

SwiftLee > Swift > Custom Operators in Swift with practical code examples

In this article

Custom Operators in Swift with practical code examples

Examples of basic operators available in swift, creating a custom operator, creating a custom compound assignment operator.

  • First, we make an extension on our Team structure
  • The operator is defined as a static method in which the method name defines the operator
  • As we’re working with structs we need to use inout which adds the requirement of having a mutable Team instance
  • Finally, we’re passing in the new member which we can add to the team with the add(_:) method

Prefix and postfix operators

  • The operator is globally defined and not tight to a specific type. This is required as we’re only working with the argument value and we don’t have a receiver type that we would otherwise define in the extension
  • We take a NSNumber as an input argument. This allows us to use the operator on any number type.
  • Note that we convert an input number into an output string. This should open your eyes to other use-cases!

Custom Infix Operator

Calculating with emojis in swift.

Custom operators in Swift to calculate with emojis

Custom Operators Playground

Featured swiftlee jobs.

  • Lead Software Engineer @ M7 Health • $105K - $185K
  • Test Automation Lead, Engineering Productivity @ Ordergroove • $140K - $170K
  • Mobile Product Manager @ Tap
  • Swift - Home
  • Swift - Introduction
  • Swift - Comments
  • Swift - Data Types
  • Swift - Variables
  • Swift - Operators
  • Swift - If Else
  • Swift - Switch Statement
  • Swift - While Loop
  • Swift - Repeat-While Loop
  • Swift - For-In Loop
  • Swift - Continue Statement
  • Swift - Break Statement
  • Swift - Math Functions

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Swift - assignment operators example

The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • %= Modulo AND assignment operator

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

The Ultimate Guide to Operators in Swift

Operators in Swift are tiny symbols that produce a result. You’ve got comparison operators, logical operators, and operators like + and – for simple math. In this tutorial, we’re diving deep into Swift’s operators, including precedence and associativity, and even write our own custom operators.

Here’s what we’ll discuss:

  • The most important operators: math, assignment, comparison, logic, ranges
  • How you can code your own custom operators
  • Important but complex topics: precedence, associativity and grouping
  • Pretty much every operator under the sun: from !a to ??

Table of Contents

Operators in swift, math operators, assignment operators, comparison operators, logical operators, range operators, really cool operators, precedence, associativity and grouping, custom operators, further reading.

What’s an operator? Let’s start with an example. Check this out:

let result = 3 + 4 print(result) // Output: 7

In the above Swift code, the + is an operator. You know it as the “plus” symbol, which is used to add one number to another and return the result.

In Swift, and in programming in general, we’ve got lots and lots of operators. This tutorial will show you how to use them, and “rules” to keep in mind, like precedence and associativity.

Before we continue, we’ll have to discuss some terminology:

  • Operator: Function that produces a result based on 1, 2 or 3 input values. We’ve got arithmetic, logical, comparison, range operators – the works!
  • Operand: The input for an operator, i.e. the numbers left and right of the + sign. You can also call them targets or parameters.
  • Expression: A combination of operators and operands, including function calls, variables, types, etc., which represents a (return) value.
  • Result: The value that’s returned by an expression, i.e. 7 is returned by the expression 3 + 4.

In this tutorial, you’ll often see the placeholders or variables a, b and c. They usually refer to the first, second and third operands (inputs) of a function. We’ll sometimes say !isLoggedIn, but it may be clearer to write !a when discussing how the logical NOT operator ! works.

In general, we can separate operators in Swift into 4 groups:

  • Math: These operators involve simple arithmetic, like addition +, multiplication = and remainder %.
  • Comparison: These operators return a boolean value, like a > b. You use them to compare numbers and strings.
  • Logical: These operators are used to evaluate and combine boolean values, such as the logical NOT operator !a.
  • Advanced: These operators provide a bit of syntactical sugar around common operations, such as the nil-coalescing operator a ?? b.

In programming we also distinguish between unary, binary and ternary operators. They refer to the number of inputs (operands) an operator has. This is important for remembering syntax, but also because it tells you something about what an operator does.

  • Unary: A unary operator has 1 operand (input). An example is !a or !isLoggedIn, for the logical NOT operator ! to invert a boolean value.
  • Binary: A binary operator has 2 operands (inputs). An example is a > b or 5 > 6, for the greater-than comparison operator >.
  • Ternary: A ternary operator has 3 operands (inputs). Swift only has 1 ternary operator, the ternary conditional operator (discussed below).

The last bit of terminology revolves around the position of the operator:

  • Prefix: A prefix operator is written before the operand, like ! in !a (logical NOT).
  • Infix: An infix operator is written in between 2 operands, like + in a + b.
  • Postfix: A postfix operator is written after the operand, like ! in a! (force unwrapping).

Quick Tip: Unary has “uno” for 1, binary has “bi” for 2, and ternary has “tri” for 3. Each of these terms comes from Latin (unus, binarius, ternarius).

Let’s start with the simplest operators of the bunch: mathematics. They work exactly as you’d expect in code, as they do in algebra class.

In Swift, we’ve got the 4 standard arithmetic operators + (plus), – (minus), * (multiplication) and / (division). Each of these operators are binary, so you’ll add one number to another with a + b for example. They (mostly) work with numbers, like integers and doubles.

3 + 4 // 7 7 – 9 // -2 4 * 4 // 16 9 / 3 // 3

You can also use + to combine 2 strings into one. This is called string concatenation. Like this:

let line = “So long” + ” and thanks for all the fish!” // Output: So long and thanks for all the fish!

Speaking of strings and integers – because Swift is a strongly typed language, you can only use operators on 2 operands that have the same type. That means – strictly speaking – you can only add 2 integers, or 2 strings, or 2 doubles to each other.

There are plenty of exceptions, though. If you try to add an integer to a double, for example:

let value = 1 + 2.0 print(value) // Output: 3.0

In the above code, Swift uses type inference to figure out that the type of value must be Double because one of its operands is Double.

Behind the scenes, Swift will convert 1 to 1.0. This makes programming considerably easier, and easier to read, because you don’t have to manually type cast that integer to a double.

Plus Minus Sign Operators

You can use the unary minus operator -a to toggle (or “flip”) the sign of a number, i.e. from positive to negative and vice versa. You can also use the unary plus operator +a, but that won’t do anything!

Let’s take a look at an example:

let positiveNumber = 42 let negativeNumber = -positiveNumber let whatNumber = -negativeNumber print(positiveNumber, negativeNumber, whatNumber) // Output: 42 -42 42

As you can see in the above code, the first number is positive, and then the -positiveNumber flips the sign to negative, and a second time back to positive, with -negativeNumber.

When we change the 3rd line to this …

let whatNumber = +negativeNumber

… the value of whatNumber is still -42. It’ll stay unchanged from negativeNumber because the +a operator doesn’t do anything!

You may find that, in day-to-day coding, the unary minus operator is impractical and hard to read. In those scenarios where you want to make explicitly clear that the sign of an expression has changed, you can use the operation a * -1. Like this:

let value = (3 + 4 / (2 * 3 * 4) – 4 / (4 * 5 * 6) + 4 / (6 * 7 * 8)) * -1 print(value) // Output: -3.145238095

The expression () * -1 is often clearer than -(). That depends on your use case, of course, but it’s good to know these little math tricks exist.

Remainder: isMultiple(of:)

The last math operator we’ll discuss is the remainder operator a % b. It’ll return the remainder of a division, i.e. what number remains if you fit a in b as many times as possible.

An example:

let value = 7 % 2 print(value) // Output: 1

The above expression 7 % 2 returns 1 because you can fit 3 times 2 in 7, which leaves 1. It’s the basic “John has 7 apples and 3 friends, how many apples are left if he gives each friend 2 apples?”

You often use the remainder operator a % b to calculate if a given number is a multiple of another number, or is divisible by that number. The most common scenario is, of course, to calculate if a given number is even or odd.

Check this out:

You use the assignment operator a = b in Swift to assign a value b to a value a. Differently said, you use the assignment operator to assign a value to a variable, constant or property.

let age = 42 print(age) // Output: 42

In the above code, we’ve assigned the integer 42 to the constant age. What’s on the right side of the = symbol is assigned to what’s on the left side of it.

That sounds so simple, but there’s more! For example, the assignment operator does not return a value. The expression age = 42 does not have a result, unlike, for example, the expression a + 4.

It’s easy to mistake the = operator with the equals operator ==, which is why Swift won’t return a value for age = 42, which helps you avoid coding errors, for example with making a typo in if age = 42 { }.

Compound Assignment Operator

Although the = assignment operator is technically the only one in Swift to assign a value to a variable, we’ve also got 4 compound assignment operators. In short, they perform an operation, like addition, and also assign the result to a variable.

Here’s an example:

var i = 3 i += 1 print(i) // Output: 4

The a += b adds b to a and assigns the result to a. It’s increasing the value of a by b. The a += b syntax is identical to a = a + b.

The above code also shows how Swift is different from other programming languages. C-style languages, like Java, have the a++ and a– operators. They increase or decrease a by one. Swift doesn’t have those, it just has a += 1 and a -= 1. (Try it, ++ really won’t work!)

In total, we’ve got 10 compound assignment operators, of which 4 are the simplest and most common. They are:

  • a += b: add and assign
  • a -= b: subtract and assign
  • a *= b: multiply and assign
  • a /= b: divide and assign

The other compound assignment operators involve bit shifting and bitwise operators. They are >=, &= (AND), |= (OR), and ^= (XOR).

It’s easy to see how += and -= work, but what about /= and *=? Let’s take a look at an example:

func power(base: Int, exponent: Int) -> Int { var result = 1

Alright, let’s move on to comparison operators. You use comparison operators in Swift to compare things with each other. A comparison operator will always return a boolean, i.e. true or false, of type Bool.

We’ve got 6 comparison operators in Swift:

  • a == b: Equal to
  • a != b: Not equal to
  • a > b: Greater than
  • a < b: Less than
  • a >= b: Greater than or equal to
  • a <= b: Less than or equal to

If you look closely, you’ll see that comparison operators have 3 groups of sorts: equal or not, greater/less than, and greater/less than or equal. Especially the >= and Identity Operators

Swift also has 2 identity operators, === and !== (“triple bar”). You use them to check if 2 values are identical to each other. Note the difference between equality and identicality:

  • Equality: Values are said to be equal when their representations are the same, according to the type you’re using.
  • Identicality: Objects are said to be identical when they refer to the exact same object.

You may find that 2 pairs shoes of the same type are equal because they have the same brand, type and color, but they aren’t identical because they’re worn by 2 different persons. Your shoes aren’t their shoes (unless you share them, which would be mildly disturbing).

Equal and Not Equal

You use a == b and a != b to check if 2 values are equal to or not equal to each other. Both of these expressions return a value that’s either true or false, which means you’ll typically use the equality operators – and other comparison operators – together with if statements.

for i in 0.. Quick Note: If you want to learn more about logic, conditionals and how to use them, check out this tutorial: Conditionals in Swift with If, Else If, Else

Greater Than, Less Than, Or Equal

Next up, let’s talk about the other 4 comparison operators. They are:

You can use these operators on numbers or on strings. They let you compare things with each other. For example, if one number is greater than the other. Just like == and !=, the above operators will always return either true or false.

Of course, 5 > 4 will always return true. In programming you often work with user input, or dynamic values from some data source, which means you’ll want to test that variable against a fixed number. That’s where comparison operators can help.

Check out the following example:

let numbers = (0.. 0 { print(“\(number) is above zero”) } } // Output: 4 is above zero, 1 is above zero, 10 is above zero

In the above code, we’re using the > operator to check if number is greater than zero. If the expression number > 0 returns true, we’ll print a bit of text. The first line of code generates an array of 10 random numbers between -10 and +10.

Let’s take a look at another example:

let likes = 3

if likes == 0 { print(“0 likes”) } else if likes == 1 { print(“1 like”) } else if likes >= 2 { print(“\(likes) likes”) } // Output: 3 likes

In the above example, we’re using the equal to == and greater than or equal to >= operators to compare the value of the likes constant. Based on its value, we print a plural/singular line of text: 0 likes, 1 like, 3 likes.

As you’ve guessed, the a >= b operator returns true if a is greater than b or if a is equal to b. It’s == and > rolled into one. But why do you need that >= operator, if you’ve got == and >?

In programming, there’s always more ways than one to solve a problem. Your job as a coder isn’t necessarily to solve the problem, but to find the approach that’s easiest to implement, or the most bug-free, or the easiest to maintain and extend in the long run. You’ve got many tools in your toolkit to get there!

Comparison operators will often revolve around the bounds of things. For example, we can assert that the last index number of an array in Swift is equal to the size of that array minus one.

The first index outside the bounds of that same array is also equal to or greater than the number of items in the array. The operators >= and Comparing Strings

Before we move on, one last thing: you can also compare strings with each other in Swift. If you give each letter from A to Z a number, you’ll see that you can compare text just as you would numbers.

let names = [“Ford”, “Arthur”, “Zaphod”, “Trillian”] print(names.sorted(by: “Arthur” print(value) // Output: true

For example, the name Ford is greater than Arthur because the F comes after the A in the alphabet.

So far, we’ve looked at mathematical operators like + and -, at (compound) assignment operators like = and +=, and at comparison operators like != and >. The fact that comparison operators, like a > b, produce boolean values is the perfect segway into the next topic: logical operators.

With logical operators you can transform boolean values. They produce a boolean value based on some logical rule. This allows you to create complex logical expressions. You can use these to take decisions in your code.

Swift has 3 common logical operators:

  • a && b: Logical AND
  • a || b: Logical OR
  • !a: Logical NOT

Logical operators take boolean values as inputs, and produce a boolean value as output. You’ll always use &&, || and ! together with true and false. As you’ve guessed, the inputs for logical operators often come from the results of comparison operators.

if threatLevel > 5 && officerRank >= 3 || isPresident { print(“!!! STRATEGIC CANDYBAR RESERVE DOORS OPENING !!!”) } else { print(“no candy for you”) }

In the above if statement, we’ve got an expression that uses many operators, including && and ||. Let’s break that down:

  • threatLevel > 5 && officerRank >= 3 (AND)
  • || isPresident (OR)

We can assert that the doors to the Strategic Candybars Reserve will open if:

  • The threat level is greater than 5 AND your officer’s rank is greater or equal to 3
  • OR you’re the president

Double-check this with me: If you’re the president, the doors will open anyway. And if your officer rank is equal or over 3, and the threat level is sufficiently high – the doors open as well. We can assert that a high threat level and officer rank merits the same “authority” as the president.

Based on what we’ve discussed so far, you see how the && (AND) and || (OR) operators will produce a boolean result based on some rules. In short, we can summarize those rules like this:

  • a && b (AND) returns true if both a and b are true
  • a || b (OR) returns true if either a or b is true

You can also put those rules in a truth table. Like this:

abANDOR truetruetruetrue truefalsefalsetrue falsetruefalsetrue falsefalsefalsefalse

See what’s happening? The OR operator will return true if either operand is true. The AND operator will only do that if they’re both true. Neat!

This leaves the !a NOT operator. How it works is simple: it’ll invert the value a. So when a is true, !a is false. And when a is false, !a is true.

Here’s a lovely truth table for the NOT operator:

aNOT truefalse falsetrue

Consequently, !!true – a valid expression – is… not not true, which is not false, which is true. Intriguing, right? You wouldn’t use that in everyday programming, but it goes to show that the logical statements in your code are solid, cast in stone. It’s either true or false – no doubt about it.

This also means you can often invert or switch logical operations to make them easier to comprehend. A logical expression says as much about what it confirms, as what it denies. Check this out:

func openDoorsIfAllowed() { if threatLevel Quick Note: When in doubt, break up your logical expression into multiple if statements. Coding 2 separate if blocks is the same as “OR” (if this, or if that), and 2 nested if blocks is the same as “AND” (if this and then if that).

The Swift Programming Language also provides operators that make your life as a coder easier, such as range operators. They don’t involve math or logic. Instead, you can use them to concisely code something that normally would have taken more code to get to the same result. This is often referred to as “syntactic sugar”.

You use range operators in Swift to denote a range between values, like from zero to 100. You can also use ranges with indices in collections, which is quite handy.

Swift has 2 range operators, in 2 groups:

  • a … b: The closed range operator, so a range from a to b including b
  • a ..< b: The half-open range operator, so a range from a to b but not including b

You can use both the … and .. Quick Note: In the above code, 2 refers to the third item in the array. This item has integer index number 2. Arrays indices in Swift start at zero!

Swift has 2 really cool operators: the nil-coalescing operator and the ternary conditional operator.

Nil-coalescing Operator

let author:String? = nil let label = author ?? “Unknown author” print(label) // Output: Unknown author

In the above code, we’re using the nil-coalescing operator a ?? b to provide a default value if author is nil. The nil-coalescing operator will return a if a is not nil, and if a is nil, it’ll return b. The ?? operator also unwraps the optional.

let author:String? = “J.K. Rowling” let label = author ?? “Unknown author” print(label) // Output: J.K. Rowling

This is the exact same code, except now the optional author has a string value instead of nil. Unlike before, the value of author is assigned to label, which subsequently prints the string “J.K. Rowling”.

The code we’ve used so far is identical to the code below, which goes to show that the a ?? b operator saves you from writing a whole lotta code.

let author:String? = nil var label = “”

if author != nil { label = author! } else { label = “Unknown author” }

print(label)

Ternary Conditional Operator

The only operator in Swift that has 3 operands is the ternary conditional operator. Let’s look at an example:

let temp = 25 // °C let value = temp > 18 ? “it’s hot” : “it’s cold” print(value) // Output: it’s hot

In the above code we’re using the a ? b : c operator to choose between b and c based on the expression a. When a is true, b is returned, and when a is false, c is returned. It’s a short-hand for a conditional.

The above code is exactly the same as this:

let temp = 25 // °C var value = “”

if temp > 18 { value = “it’s hot” } else { value = “it’s cold” } // it’s hot

Just as the nil-coalescing operator, the ternary conditional is much more concise. This usually – not always – makes your code easier to read and comprehend.

Did you know you can implement the ?? operator with ?:, and vice versa? It’s a bit silly, of course – but nevertheless, you can, because they’re both syntactic sugar around more verbose bits of code. Check this out!

1. a ? b : c with a ?? b:

let temp = 25 // °C let value = { if temp > 18 { return “it’s hot” } else { return nil } }() ?? “it’s cold”

print(value) // Output: it’s hot 2: a ?? b with a ? b : c:

let author:String? = nil let label = author != nil ? author! : “Unknown author” print(label) // Output: Unknown author

Before we call it quits, we’ll have to discuss 3 important but often overlooked concepts for working with operators in Swift. They are:

  • Precedence: When using multiple operators together, which operations are done before the others?
  • Associativity: When 2 operators have the same precedence, do the operands on the left or the right belong to the operator?
  • Grouping: Changing the precedence of operators by grouping operators together within parentheses ( ) or emphasizing their existing order by adding parentheses ( ) (without changing their order).

First, let’s talk about precedence. It sounds more complex than it actually is! Check out the following calculation:

let a = 2 + 3 * 4 print(a) // ??? What’s the value of a in the above code?

*tick* *tock* *tick* *tock*

It’s 14! Because multiplication goes before addition, so the result 3 * 4 is calculated first (12) to which 2 is added (14). The other way around – which is incorrect – would be 2 + 3 = 5 times 4 is 20.

This is a simple example, but it gets more complicated if you consider all operators that Swift has. Precedence, i.e. the order of operators, not only affects arithmetic, but also extends to comparison- and logical operators.

Let’s discuss a few ways of looking at this. In practical, day-to-day Swift programming, you’ll need to remember this:

  • Precedence rules follow the rules you learned in math: * / + –
  • Math operators go before comparison operators go before logical operators
  • Logic operator rules: && (AND) goes before || (OR)
  • Prefix operators !a, +a and -a go first

That’s it! This should get you pretty far. When in doubt, you can always look up the documentation on precedence rules in Swift.

But what’s the real explanation here, beyond shorthands? In reality, precedence rules are divided into groups. The precedence rule for the group determines what, for example, the order of logical operator && is in combination with >= and +.

In short, the first-to-last order is:

  • MultiplicationPrecedence for * / %
  • AdditionPrecedence for + –
  • RangeFormationPrecedence for ranges
  • CastingPrecedence for type casting operators
  • NilCoalescingPrecedence for ??
  • ComparisonPrecedence for all comparison operators
  • LogicalConjunctionPrecedence for && ||
  • TernaryPrecedence for ?:
  • AssignmentPrecedence for all assignment operators

Associativity In the above list for precedence you can see that multiple operators are grouped together. How do you determine the order of operators in a group, when they have the same importance? That’s where associativity comes in.

You’ve got 3 types of associativity:

  • Left-associative: Grouped from the left, so left-most operator “grabs” left-most operands first
  • Right-associative: Grouped from the right, so right-most operator “grabs” the operands first
  • Non-associative: Operators cannot be grouped (most notably, comparison operators b/c their input type is different from their output type)

Here’s a simple example:

let a = 7 – 4 + 2 print(a) // Output: ?

We’ve seen in the list for precedence that both the a + b and a – b operators have the same precedence group. When you combine them, which operation goes first?

  • (7 – 4) + 2 = 5 (left-associative)
  • 7 – (4 + 2) = 1 (right-associative)

Arithmetic operators like + – * / are left-associative. This means that, when they’re used together, we can “grab” the left-most operation together. Kinda lika a cowboy throwing a lasso/rope around them. Like this:

let a = (7 – 4) + 2 print(a) // Output: 5

The operation 7 – 4 = 3 goes first, after which 2 is added, resulting in 5. Because – and + are left-associative, the left-most operator groups its operands (7 and 4), which goes first, and then + goes second. This results in a definitive order of operations!

In short, associativity rules for operators in Swift are as follows:

  • * / % + – are left-associative
  • ?? and ?: are right-associative
  • && and || are left-associative
  • = and assignment operators are right-associative

What about groups that have no associativity? In Swift, all comparison operators are non-associative. They do not have associativity rules between them. How is that even possible!?

It’s simpler than it looks. Because comparison operators take numbers (and strings) as input, but produce booleans, you’d end up with a type conflict if they were left- or right-associative. It’s only logical to either avoid that conflict, or to throw an error because the expression is invalid.

let a = 5 > c = 0 && userLevel > 3 || !isLoggedIn // What’s the order? Comparison first, then &&, then ||

Who grabs the operand userLevel > 3 in the above code? It’s the &&, because AND goes before OR. There is no conflict among the comparison operators, because they aren’t combined and belong to their own group.

You can create groups in your expressions with parentheses ( ). This enables you to change the order of operations, because the expressions within the group are evaluated before the ones outside of it.

You can do this for 2 reasons:

  • Improve the readability of your code, to make implicit precedence rules clearer
  • Change the order of operations for expressions that would otherwise return an incorrect result

Let’s go back to that previous conundrum with + and *. This one:

let a = 2 + 3 * 4 // Output: 14

What if you actually needed 20 here, instead of 14? That’s when you can use grouping with parentheses to get to the right result. Like this:

let b = (c + d) * e

In the above code, the expression c + d is calculated before multiplying its result with e. If you wouldn’t have used the parentheses, the calculation d * e would have gone first.

The other reason to use grouping with parentheses is to make an expression clearer. We’ve discussed precedence and associativity rules, but they aren’t always as easy to remember. On top of that, most conditional expressions involve complex variable names that can impair readability.

You can help yourself and other developers by grouping expressions together, according to their pre-existing precedence rules, to emphasize the order of operations. Take these 2 expressions, for example:

if threatLevel > 5 && officerRank >= 3 || isPresident { if (threatLevel > 5 && officerRank >= 3) || isPresident {

The results of both conditionals are exactly the same. We know that && goes before ||, and the officerRank >= 3 isn’t grabbed by the || operator. Instead, they’re left-associative, which means it’s an operand for the && operator and not ||.

We’re emphasizing this order with the parentheses. At a glance, we can see that the code inside the parentheses is evaluated first. Its result is then evaluated with || isPresident.

You’ll want to use this sparingly, of course, and not as an excuse to avoid learning more about precedence rules and associativity. If you add parentheses for all precedence rules involved in your expression, you lose the effect of hinting at what goes first.

Last but not least: custom operators. You can build your own operators in Swift! Let’s take a look at an example:

infix operator ^^

func ^^ (base: Int, exponent: Int) -> Int { var result = 1

  • Operator declaration, like infix operator ^^
  • Implementation of the operator with a function

In the above code, on the first line, we’re creating a custom operator ^^. It’s an infix operator, so it’ll go between 2 operands. We could also have chosen postfix or prefix. The declaration also includes the word operator.

Then, we’re declaring a function with the “name” of the operator. We’re giving this function 2 parameters, one on each side of the operator. You’ll often see these parameters as lhs and rhs, meaning left-hand side and right-hand side. For our ^^ operator, it makes more sense to call them base and exponent.

In the last part of the code, we’re putting the a ^^ b operator to good use. 2 to the 4th power is 16!

You’ll notice that the ^^ operator, as implemented above, is limited to the integer Int type. You can only use it with integers; use it with anything else and you’ll get a type error.

The power of custom operators lies within its combination with existing Swift types. You can use extensions, generics, protocols and “where” to add custom types to existing types in Swift. Thanks to the flexibility of Swift’s type system, you can declare your custom operator once and use it with any or all types.

prefix operator ∑

extension Sequence where Self.Element: Numeric { static prefix func ∑ (items: Self) -> Self.Element { return items.reduce(0, { $0 + $1 }) } }

The above code adds a prefix operator ∑ (Capital sigma) to the Sequence type, via an extension. The operator produces the sum of the sequence’s members.

Using the where keyword, this extension only applies to sequences whose elements are numeric. You can use the ∑ operator on arrays, sets, sequences, ranges of integers, doubles, floats, etcetera.

∑(0…10) // 55

∑[1, 2, 3] // 6

∑[0.1, 3.9, 4.4, -2] // 6.4

∑[“Ford”, “Trillian”, “Arthur”].map { $0.count } // 18

Quick Tip: You can also add existing operators to custom types in Swift. You can, for example, add the a + b operator to your own struct, to be able to add 2 of the struct’s instances to each other! The code you need to do this is exactly the same as discussed in this section, except for the operator declaration.

Pfew! Operators look so small but they can do so much. In essence, they’re tiny functions you can stick between a bunch of operands and voilá – you’ve got a result.

In this tutorial, we’ve discussed math-, assignment-, comparison-, range- and logical operators. We came across really cool operators like ?? and :?. We’ve talked about operator precedence, associativity and grouping. And finally, we even built our own custom operator.

Related Articles

  • How to use Trello for Project Management? [Trello Beginner’s Guide]
  • Apple recently removed Facebook’s Onavo security app from the App Store for Non-Compliance to Privacy Guidelines
  • How to Create a Career Counselling Chatbot? (Step-by-Step Guide)
  • 9 Essential Elements To Include In Your App
  • 21 Best Domain Name Generators for Website Name Ideas
  • DynamoDB vs MongoDB: Which NoSQL Database is Right for Your Project? [Top Integrations]
  • How to Retain Customers With a Help Desk Software?
  • Asana Vs. Jira [Which is right for project management?]
  • How to increase your app downloads and improve your app ranking?
  • App Development at home – A Beginner’s Guide

Head of SEO at Appy Pie

Most Popular Posts

  • How to Create an Android App [A Guide to Creating Android Apps in 2024] By Deepak Joshi  | December 21, 2023
  • How To: Pass Data Between View Controllers in Swift By Abhinav Girdhar  | October 19, 2023

what is assignment operator in swift

About 15 mins

Learning Objectives

Assigning a value, basic arithmetic, compound assignment, order of operations, numeric type conversion, complete the lab, before taking the quiz.

  • Challenge +100 points

Learn About Operators

After completing this unit, you’ll be able to:

  • Execute basic Swift mathematic operations.
  • Add two numbers of different types together.
  • Find the remainder of a division operation.

Operators are the symbols that make your code work. You use them to do things like check, change, or combine values. Swift has many types of operators, including ones to perform mathematical operations, logical operations, and complex assignments.

In this unit, you'll learn about some of the operators in the Swift language, including basic math operators for addition ( + ), subtraction ( – ), multiplication ( * ), and division ( / ). 

Use the = operator to assign a value. The name on the left is assigned the value on the right.

This code declares that Luke is your favorite person:

The = operator is also used to modify or reassign a value.

The following code declares a shoeSize variable and assigns 8 as its value. The value is then modified to 9 :

You can use the + , - , * , and / operators to perform basic math functionality:

You can use operators to perform arithmetic using the values of other variables:

An operator can even reference the current variable, updating it to a new value:

For decimal-point precision, you can do the same operations on Double values:

When you use the division operator ( / ) on Int values, the result will be an Int value rounded down to the nearest whole number, because the Int type only supports whole numbers:

If you explicitly declare constants or variables as Double values, the results will include decimal values.

Make sure to use Double values whenever your code requires decimal-point accuracy.

An earlier code snippet updated a variable by adding a number to itself:

But there's a better way to modify a value that's already been assigned. You can use a compound assignment operator, which adds the = operator after an arithmetic operator:

Compound assignment operators help you write cleaner, more concise code.

Mathematic operations always follow a specific order. Multiplication and division have priority over addition and subtraction, and parentheses have priority over all four.

Consider the following variables:

Then consider the following calculations:

In the first line above, multiplication takes precedence over addition. In the second line, the parentheses get to do their work first.

As you've learned, you can't mix and match number types when performing mathematical operations.

For example, the following will produce a compiler error, because integer is an Int value and decimal is a Double value:

To enable the code to finish, you can create a new Double value from the integer by prefixing the type you want to convert it to:

In the revised code, Double(integer) creates a new Double value for the Int value integer , enabling the compiler to add it to decimal and assign the result to pi .

Ready to get hands-on experience with Swift? Practice what you learned with the exercises in Lab - Operators.playground .

We're taking a unique approach to testing your knowledge about Operators. Below are some Swift code samples. In the quiz, we ask you questions that will require you to assess the code and verify you understand how it works. Good luck!

For Quiz Question 1

For Quiz Question 2

  • Swift Programming Language Guide: Basic Operators
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities

Javatpoint Logo

  • Interview Q

Swift Tutorial

Control statement, swift loops, swift strings, swift functions, swift collection.

JavaTpoint

Assignment operator is used to initialize or update the values of both its operands. For example, , the assignment operator (=) initializes or updates the value of a with the value of b.

If the right side operand contains the multiple values, its elements can be decomposed into multiple constants or variables at once:

Swift 4 assignment operator does not itself return a value like C and Objective C assignment operators do.

So, the following statement is invalid in Swift 4:





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output

Python Operators

Python flow control.

Python if...else Statement

  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python

Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

Precedence and Associativity of Operators in Python

  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python 3 Tutorial

  • Python Strings
  • Python any()

Operators are special symbols that perform operations on variables and values. For example,

Here, + is an operator that adds two numbers: 5 and 6 .

  • Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,

Here, - is an arithmetic operator that subtracts two values or variables.

Operator Operation Example
Addition
Subtraction
Multiplication
Division
Floor Division
Modulo
Power

Example 1: Arithmetic Operators in Python

In the above example, we have used multiple arithmetic operators,

  • + to add a and b
  • - to subtract b from a
  • * to multiply a and b
  • / to divide a by b
  • // to floor divide a by b
  • % to get the remainder
  • ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

Here, = is an assignment operator that assigns 5 to x .

Here's a list of different assignment operators available in Python.

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponent Assignment

Example 2: Assignment Operators

Here, we have used the += operator to assign the sum of a and b to a .

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False . For example,

Here, the > comparison operator is used to compare whether a is greater than b or not.

Operator Meaning Example
Is Equal To gives us
Not Equal To gives us
Greater Than gives us
Less Than gives us
Greater Than or Equal To give us
Less Than or Equal To gives us

Example 3: Comparison Operators

Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,

Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .

Operator Example Meaning
a b :
only if both the operands are
a b :
if at least one of the operands is
a :
if the operand is and vice-versa.

Example 4: Logical Operators

Note : Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)

Operator Meaning Example
Bitwise AND x & y = 0 ( )
Bitwise OR x | y = 14 ( )
Bitwise NOT ~x = -11 ( )
Bitwise XOR x ^ y = 14 ( )
Bitwise right shift x >> 2 = 2 ( )
Bitwise left shift x 0010 1000)

6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.

  • Identity operators

In Python, is and is not are used to check if two values are located at the same memory location.

It's important to note that having two variables with equal values doesn't necessarily mean they are identical.

Operator Meaning Example
if the operands are identical (refer to the same object)
if the operands are not identical (do not refer to the same object)

Example 4: Identity operators in Python

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.

  • Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).

In a dictionary, we can only test for the presence of a key, not the value.

Operator Meaning Example
if value/variable is in the sequence
if value/variable is in the sequence

Example 5: Membership operators in Python

Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .

  • Precedence and Associativity of operators in Python

Table of Contents

  • Introduction
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python Bitwise operators
  • Python Special operators

Write a function to split the restaurant bill among friends.

  • Take the subtotal of the bill and the number of friends as inputs.
  • Calculate the total bill by adding 20% tax to the subtotal and then divide it by the number of friends.
  • Return the amount each friend has to pay, rounded off to two decimal places.

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

  • Programming

Rahul Awati

  • Rahul Awati

What is an operator in mathematics and programming?

In mathematics and computer programming , an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.

Depending on its type, an operator manipulates an arithmetic or logical value, or operand, in a specific way to generate a specific result. From handling simple arithmetic functions to facilitating the execution of complex algorithms, like security encryption , operators play an important role in the programming world.

Mathematical and logical operators should not be confused with a system operator , or sysop, which refers to a person operating a server or the hardware and software in a computing system or network.

Operators and logic gates

In computer programs, Boolean operators are among the most familiar and commonly used sets of operators. These operators work only with true or false values and include the following:

These operators and variations, such as XOR, are used in logic gates .

Boolean operators can also be used in online search engines , like Google. For example, a user can enter a phrase like "Galileo AND satellite" -- some search engines require the operator be capitalized in order to generate results that provide combined information about both Galileo and satellite.

Types of operators

There are many types of operators used in computing systems and in different programming languages. Based on their function, they can be categorized in six primary ways.

1. Arithmetic operators

Arithmetic operators are used for mathematical calculations. These operators take numerical values as operands and return a single unique numerical value, meaning there can only be one correct answer.

The standard arithmetic operators and their symbols are given below.

+

Addition (a+b)

This operation adds both the operands on either side of the + operator.

-

Subtraction (a-b)

This operation subtracts the right-hand operand from the left.

*

Multiplication (a*b)

This operation multiplies both the operands.

/

Division (a/b)

This operation divides the left-hand operand by the operand on the right.

%

Modulus (a%b)

This operation returns the remainder after dividing the left-hand operand by the right operand.

2. Relational operators

Relational operators are widely used for comparison operators. They enter the picture when certain conditions must be satisfied to return either a true or false value based on the comparison. That's why these operators are also known as conditional operators.

The standard relational operators and their symbols are given below.

==

Equal (a==b)

This operator checks if the values of both operands are equal. If yes, the condition becomes TRUE.

!=

Not equal (a!=b)

This operator checks if the values of both operands are equal. If not, the condition becomes TRUE.

>

Greater than (a>b)

This operator checks if the left operand value is greater than the right. If yes, the condition becomes TRUE.

<

Less than (a<b)

This operator checks if the left operand is less than the value of right. If yes, the condition becomes TRUE.

>=

Greater than or equal (a>=b)

This operator checks if the left operand value is greater than or equal to the value of the right. If either condition is satisfied, the operator returns a TRUE value.

<=

Less than or equal (a<=b)

This operator checks if the left operand value is less than or equal to the value of the right. If either condition is satisfied, the operator returns a TRUE value.

3. Bitwise operators

Bitwise operators are used to manipulate bits and perform bit-level operations . These operators convert integers into binary before performing the required operation and then showing the decimal result.

The standard bitwise operators and their symbols are given below.

&

Bitwise AND (a&b)

This operator copies a bit to the result if it exists in both operands. So, the result is 1 only if both bits are 1.

|

Bitwise OR (a|b)

This operator copies a bit to the result if it exists in either operand. So, the result is 1 if either bit is 1.

^

Bitwise XOR (a^b)

This operator copies a bit to the result if it exists in either operand. So, even if one of the operands is TRUE, the result is TRUE. However, if neither operand is TRUE, the result is FALSE.

~

Bitwise NOT (~a)

This unary operator flips the bits (1 to 0 and 0 to 1).

4. Logical operators

Logical operators play a key role in programming because they enable a system or program to take specific decisions depending on the specific underlying conditions. These operators take Boolean values as input and return the same as output.

The standard logical operators and their symbols are given below.

&&

Logical AND (a&&b)

This operator returns TRUE only if both the operands are TRUE or if both the conditions are satisfied. It not, it returns FALSE.

||

(a||b)

This operator returns TRUE if either operand is TRUE. It also returns TRUE if both the operands are TRUE. If neither operand is true, it returns FALSE.

!

Logical NOT (!a)

This unary operator returns TRUE if the operand is FALSE and vice versa. It is used to reverse the logical state of its (single) operand.

5. Assignment operators

Assignment operators are used to assign values to variables. The left operand is a variable, and the right is a value -- for example, x=3.

The data types of the variable and the value must match; otherwise, the program compiler raises an error, and the operation fails.

The standard assignment operators and their symbols are given below.

=

Assignment (a=b)

This operator assigns the value of the right operand to the left operand (variable).

+=

Add and assign (a+=b)

This operator adds the right operand and the left operand and assigns the result to the left operand.

Logically, the operator means a=a+b.

-=

Subtract and assign (a-=b)

This operator subtracts the right operand from the left operand and assigns the result to the left operand.

Logically, the operator means a=a-b.

*=

Multiply and assign (a*=b)

This operator multiplies the right operand and the left operand and assigns the result to the left operand.

Logically, the operator means a=a*b.

/=

Divide and assign (a/=b)

This operator divides the left operand and the right operand and assigns the result to the left operand.

Logically, the operator means a=a/b.

%=

Modulus and assign (a%=b)

This operator performs the modulus operation on the two operands and assigns the result to the left operand.

Logically, the operator means a=a%b.

6. Increment/decrement operators

The increment/decrement operators are unary operators, meaning they require only one operand and perform an operation on that operand. They sometimes are called monadic operators .

The standard increment/decrement operators and their symbols are given below.

++

Post-increment (a++)

This operator increments the value of the operand by 1 after using its value.

--

Post-decrement (a--)

This operator decrements the value of the operand by 1 after using its value.

++

Pre-increment (++a)

This operator increments the value of the operand by 1 before using its value.

--

Pre-decrement (--a)

This operator decrements the value of the operand by 1 before using its value.

See also: proximity operator , search string , logical negation symbol , character and mathematical symbols .

Continue Reading About operator

  • How to become a good Java programmer without a degree
  • How improving your math skills can help in programming
  • 10 best IT certs for beginners
  • Top 22 cloud computing skills to boost your career in 2022
  • Binary and hexadecimal numbers explained for developers

Related Terms

NBASE-T Ethernet is an IEEE standard and Ethernet-signaling technology that enables existing twisted-pair copper cabling to ...

SD-WAN security refers to the practices, protocols and technologies protecting data and resources transmitted across ...

Net neutrality is the concept of an open, equal internet for everyone, regardless of content consumed or the device, application ...

A proof of concept (PoC) exploit is a nonharmful attack against a computer or network. PoC exploits are not meant to cause harm, ...

A virtual firewall is a firewall device or service that provides network traffic filtering and monitoring for virtual machines (...

Cloud penetration testing is a tactic an organization uses to assess its cloud security effectiveness by attempting to evade its ...

Regulation SCI (Regulation Systems Compliance and Integrity) is a set of rules adopted by the U.S. Securities and Exchange ...

Strategic management is the ongoing planning, monitoring, analysis and assessment of all necessities an organization needs to ...

IT budget is the amount of money spent on an organization's information technology systems and services. It includes compensation...

ADP Mobile Solutions is a self-service mobile app that enables employees to access work records such as pay, schedules, timecards...

Director of employee engagement is one of the job titles for a human resources (HR) manager who is responsible for an ...

Digital HR is the digital transformation of HR services and processes through the use of social, mobile, analytics and cloud (...

A virtual agent -- sometimes called an intelligent virtual agent (IVA) -- is a software program or cloud service that uses ...

A chatbot is a software or computer program that simulates human conversation or "chatter" through text or voice interactions.

Martech (marketing technology) refers to the integration of software tools, platforms, and applications designed to streamline ...

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

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.

Can I initialize a variable using a custom assignment operator?

Recently I was experimenting with assignment operators in Swift and came across a problem, which I couldn't find the solution for.

Consider the following architecture:

Seems pretty straightforward, but imagine that MyStruct accepts 20 boxed properties – each of them requires "unboxing" by accessing the value property of a Box instance. Now imagine having 20 versions of MyStruct .

That would lead to hundreds of .value lines, which is quite a lot. Instead, to reduce the code mess, I would like to use a custom assignment operator, which implicitly "unboxes" a Box and assigns its value to a variable.

Consider this simple example (with no optionality support, etc.):

Ideally, I would like to use <|= operator right away, like this:

But unfortunately (and quite predictably?), this doesn't work, as myProperty variable is not initalized before used in a function:

Can I ensure the compiler that my assignment operator function always initializes the variable (a.k.a. its lhs operand)? Also, if you have an idea of a different approach, feel free to comment.

Note: The actual case is more complicated and requires more "unboxing" than just accessing a value propterty of a Box structure.

  • operator-overloading
  • variable-assignment

akashivskyy's user avatar

  • Your problem is not amenable to using arrays of boxes and properties? init(boxedProperties: [Box<String>]) { self.myProperties = boxedProperties.map { %0.value } } With this, 20 or 200 properties, no matter. –  GoZoner Jan 10, 2015 at 23:36
  • @GoZoner No. It's actually init(anEnumValue: MyEnum) in the real-life case. The enum value holds different associated values, which need to be double-"unboxed". –  akashivskyy Jan 10, 2015 at 23:41
  • Unlike other Swift 'assignment' operators (other than actual assignment with '=') you don't need an inout parameter - because, as you know, you never actually reference the value. But, on the surface you are trading off: self.myProperty <|= boxedProperty for self.myProperty = boxedProperty.value . I don't appreciate the advantage to an operator in this case but I'm willing to admit I must not see your actual issue. –  GoZoner Jan 10, 2015 at 23:51
  • @GoZoner The real unboxing takes a couple of lines (5-10), including a switch statement. –  akashivskyy Jan 11, 2015 at 10:48

4 Answers 4

You can't do this the way you're describing, since assignment operators use both of the operands in the expression, which you can't do with an uninitialized variable. What about using a prefix operator that returns the boxed value instead?

Nate Cook's user avatar

  • I thought about that too, using an infix operator just seems more natural (since I'm actually developing an open-source framework). –  akashivskyy Jan 7, 2015 at 20:07
  • In that case your only way would be to give default values to all properties first, then use the infix operator to unbox / process. –  Nate Cook Jan 7, 2015 at 20:08
  • Or make them optional. Nasty stuff in both cases. –  akashivskyy Jan 7, 2015 at 20:09
  • I'll wait a little bit for other opinions (if any) and accept this answer if none of them meets my expectations as high as yours. :) –  akashivskyy Jan 7, 2015 at 20:11
  • trips up on swift 4 - Operator should no longer be declared with body –  johndpope Sep 18, 2018 at 17:54

There is no reason to use syntax to accomplish your goal. Just define a function that encapsulates your ' switch statement with a couple of lines'. Make sure that that function is bound with let so that it is accessible within init() As such:

The 'cost' of this is an 'extra' instance variable for myUnboxer but that could quickly become an advantage when the details of unboxing become structure specific - at which point you'll initialize MyStruct with the unboxer as well.

For me, in a language that has closures and first-class functions it is usually a mistake to invent syntax - unless one is actively defining a sublanguage. Having statements with special evaluation rules (aka 'syntax') confuses.

GoZoner's user avatar

  • It also has operators as first-class functions. ;) I think an assignment operator should be able to "initialize" a variable. –  akashivskyy Jan 11, 2015 at 17:32

I have used enums to store properties of objects, like this:

I then have an extension to NSTextField that includes a function called assignProps that takes an array of TextFieldProps :

That allows me, when I need to set or change the properties of a NSTextField, to just pass an array of TextFieldProps to assign , which updates everything in one pass using reduce .

I take it you are trying to use something similar, only with a generic Box that holds the value inside of it. Perhaps there is a way to modify the technique above to suit your purposes. It is hard to give you a clear answer without knowing more about the structure of the enums and Box ed values that you are working with.

What I can say is that if you are trying to set the value of 20 properties, somewhere there will be 20 assignment calls, regardless of whether or not you are using a custom operator.

When I use a Box type object (which I sometimes do), I have a couple of different custom functions for them. One of them is just called o , for "open":

I know it doesn't directly answer the question you asked about custom assignment operators, but if you shorten up the init label to b and use a function named o , you've gotten the whole thing down to 4 characters, o(b) . That's about as short and efficient as you can make it, and o(b) , to me, intuitively looks like shorthand for opened box , so the code is not too confusing.

You may want to restrict the scope of o so that later users of your framework can use o as a variable name if they want to. You can actually create o inside MyStruct 's init function like this:

o is now a closure, defined inside of the init function and is limited in scope to just that function. You can still use o as a variable name anywhere else in the code that you want without any conflicts.

Aaron Rasmussen's user avatar

I think this is solvable by using default property values. E.g. something like:

0x416e746f6e's user avatar

  • Yes it is, but the properties shouldn't be optional. –  akashivskyy Jan 15, 2015 at 8: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 swift operator-overloading variable-assignment or ask your own question .

  • The Overflow Blog
  • Introducing Staging Ground: The private space to get feedback on questions...
  • How to prevent your new chatbot from giving away company secrets
  • Featured on Meta
  • The [tax] tag is being burninated
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Print all correct parenthesis sequences of () and [] of length n in lexicographical order
  • Automatically typeset subscripts upright - how to make it compatible with greek letters?
  • Effects if a human was shot by a femtosecond laser
  • Could a delayed choice Aharonov-Bohm experiment be used for FTL information transfer?
  • What’s the history behind Rogue’s ability to touch others directly without harmful effects in the comics?
  • How is this function's assembly implementing the conditional?
  • In Acts 10 why does Peter not know the gospel is not only for the Jewish people?
  • Can LLMs have intention?
  • What is the translation of a feeler in French?
  • Is a weak version of the three sets Lemma provable in ZF?
  • Who are the mathematicians interested in the history of mathematics?
  • Why does SQL-Server Management Studio change "Execute Query" into "Save Results"?
  • On a planet with 6 moons, how often would all 6 be full at the same time?
  • How to typeset commutative diagrams
  • A phrase that means you are indifferent towards the things you are familiar with?
  • Why does White castle into Black's attack in the King's Indian, and then run away afterwards?
  • How did ALT + F4 become the shortcut for closing?
  • Point and click exploration game from the 1990s
  • What caused localized cracking and peeling of wall paint and how should I go about fixing it?
  • Is it true that engines built in Russia are still used to launch American spacecraft?
  • Looping counter extended
  • What is the U.N. list of shame and how does it affect Israel which was recently added?
  • In Catholicism, is it OK to join a church in a different neighborhood if I don't like the local one?
  • Calculating Living Area on a Concentric Shellworld

what is assignment operator in swift

IMAGES

  1. Hour 3. Using Operators in Swift

    what is assignment operator in swift

  2. Compound assignment operators

    what is assignment operator in swift

  3. Swift Programming Tutorial

    what is assignment operator in swift

  4. Assignment operator tutorial (Swift Programming Language Reference App

    what is assignment operator in swift

  5. Operators in Swift

    what is assignment operator in swift

  6. 18. Assignment Operator

    what is assignment operator in swift

VIDEO

  1. Assignment Operator in C Programming

  2. The Assignment Operator in Java

  3. 4.7 Left and Right Shift Operator in Java

  4. Division Operator || Assignment Operator || Relational Algebra || DBMS

  5. #9 JavaScript Assignment Operators

  6. Assignment Operators in C

COMMENTS

  1. Basic Operators

    Like C, Swift provides compound assignment operators that combine assignment (=) with another operation. One example is the addition assignment operator (+=): var a = 1 a += 2 // a is now equal to 3. The expression a += 2 is shorthand for a = a + 2. Effectively, the addition and the assignment are combined into one operator that performs both ...

  2. Swift

    Swift - Assignment Operators - Assignment Operators are the special operators. They are used to assign or update values to a variable or constant. In the assignment operators, the right-hand side of the assignment operator is the value and the left-hand side of the assignment operator should be the variable to which the value wil

  3. Swift Operators (With Examples)

    2. Swift Assignment Operators. Assignment operators are used to assign values to variables. For example, // assign 5 to x var x = 5. Here, = is an assignment operator that assigns 5 to x. Here's a list of different assignment operators available in Swift.

  4. Documentation

    For information about the operators provided by the Swift standard library, see Operator Declarations. Note. At parse time, an expression made up of infix operators is represented as a flat list. This list is transformed into a tree by applying operator precedence. ... The assignment operator sets a new value for a given expression. It has the ...

  5. Essential Swift Operators Every iOS Developer Should Master

    These include bitwise operators for manipulating binary data, and compound assignment operators (such as += and *=) that combine assignment (=) with another operation. Let's explore the bitwise and assignment operator used in Swift: Bitwise Operators in Swift. Bitwise operators allow operations on individual bits of integers.

  6. Swift

    Basic operators in Swift are commonly used to evaluate, reassign, and combine values.. Assignment Operator. The assignment operator = in Swift is the same as in most other languages and serves the same purpose. It is used to initialize or reassign a variable to some value. In Swift, unlike some other high-level programming languages like C or Java, the assignment operator does not return any ...

  7. Hour 3: Using Operators in Swift

    The Assignment Operator. There is just one assignment operator in Swift, as in other languages, and that is the equal sign (=). The assignment operator takes the calculated or literal value on the right side of the equal sign and assigns it to the variable or constant on the left side of the equal sign.

  8. 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 ...

  9. Assignment operators

    Assignment Operator (=): The assignment operator is used to assign a value to a variable or constant.For example: let x = 10 var y = 5 y = x // y is now 10. Compound Assignment Operators: Compound ...

  10. Creating custom operators in Swift

    Common 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.

  11. Swift

    Assignment Operators = (Equal): This operator is used to assign values from the right side variable to the left side variable. ... In swift operator, precedence is used to find the grouping terms in the given expression. Also, used to evaluate the expression. For example, y = 3 + 4 * 2, here * has the highest precedence so first, we solve 4 *2 ...

  12. 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) }

  13. Custom Operators in Swift with practical code examples

    Custom operators are also known as advanced operators and allow you to combine two instances with a self-chosen infix, prefix, postfix, or assignment operator. When developing code in Swift we're all using the default operators quite often. Adding up two numbers by using the + sign is an example of making use of basic operators available in ...

  14. Swift assignment operators example

    The example below shows the usage of assignment and compound assignment operators: = Assignment operator. += Addition AND assignment operator. -= Subtraction AND assignment operator. *= Multiply AND assignment operator. /= Division AND assignment operator. %= Modulo AND assignment operator. var a = 25.0 var b = 25 print("a = \(a) b = \(b) \n ...

  15. The Ultimate Guide to Operators in Swift

    Compound Assignment Operator. Although the = assignment operator is technically the only one in Swift to assign a value to a variable, we've also got 4 compound assignment operators. In short, they perform an operation, like addition, and also assign the result to a variable. Here's an example: var i = 3 i += 1 print(i) // Output: 4

  16. Learn About Operators

    Operators are the symbols that make your code work. You use them to do things like check, change, or combine values. Swift has many types of operators, including ones to perform mathematical operations, logical operations, and complex assignments. In this unit, you'll learn about some of the operators in the Swift language, including basic math ...

  17. Swift Assignment Operator

    Assignment operator is used to initialize or update the values of both its operands. For example, here (a = b), the assignment operator (=) initializes or updates the value of a with the value of b. Swift 4 assignment operator does not itself return a value like C and Objective C assignment operators do. // This is not valid, because x = y does ...

  18. swift

    The nil-coalescing operator ( a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a. ?? - indicates default value assignment, when your variable has a nil value.

  19. Python Operators (With Examples)

    Example 2: Assignment Operators # assign 10 to a a = 10 # assign 5 to b b = 5 # assign the sum of a and b to a a += b # a = a + b print(a) # Output: 15. Here, we have used the += operator to assign the sum of a and b to a. Similarly, we can use any other assignment operators as per our needs.

  20. What is an operator in programming?

    5. Assignment operators. Assignment operators are used to assign values to variables. The left operand is a variable, and the right is a value -- for example, x=3. The data types of the variable and the value must match; otherwise, the program compiler raises an error, and the operation fails.

  21. Assign conditional expression in Swift?

    This kind of assignment is good for functional style / immutability. The expressions have a return value in this case. Note2: it's a general question, this is just a simplified example, imagine e.g. a switch case with a lot of values, pattern matching, etc.

  22. 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.

  23. swift

    Unlike other Swift 'assignment' operators (other than actual assignment with '=') you don't need an inout parameter - because, as you know, you never actually reference the value. But, on the surface you are trading off: self.myProperty <|= boxedProperty for self.myProperty = boxedProperty.value.I don't appreciate the advantage to an operator in this case but I'm willing to admit I must not ...