Matteo Manferdini

Swift and iOS Development Best Practices

Write Shorter Conditions with the Swift Ternary Operator

The ternary operator is a conditional operator that you can use to write complex conditions using just one line of code. It is straightforward to use and powerful.

In this article, I will highlight the most common use cases of the ternary operator in Swift. I will also review the advantages and disadvantages of writing conditions using the ternary operator instead of if-else statements.

  • This article is part of the Learn Swift series.

swift ternary operator assignment

Architecting SwiftUI apps with MVC and MVVM

Table of contents, writing conditions using only one line of code, assign values to constants and variables based on certain conditions, calling functions based on certain conditions, writing nested conditions in a single statement using multiple ternary operators.

The ternary operator is a shorthand for if-else statements.

Let’s take, for example, a simple calculator app with two basic operations: addition and subtraction.

The above logic can be rewritten using just one line of code with the ternary operator.

The t ernary operator works with three things: a condition and two statements. The statement executed if the condition is true is placed after the question mark. The statement executed if the condition is false is placed after the colon.

You may think the ternary operator is just syntactic sugar for simple if…else statements. But it is so much more. Let’s look at some advantages of using the ternary operator in your code.

Let’s say the calculator app also determines the minimum and maximum values of two given whole numbers.

min and max are assigned values twice in the above if-else statements. You can simplify this logic with a ternary operator.

The ternary operator sets both min and max to either first or second . min and max are now only assigned values once.

You can combine the previous if-else statements into a single statement.

However, min and max are assigned values twice. You may think that you can simplify things with the ternary operator.

However, the code crashes because you cannot have multiple instructions after either the question mark or the colon of the ternary operator.

The previous if-else statement can be rewritten with a tuple instead.

The (min, max) tuple is assigned values twice. The ternary operator works as expected.

The tuple stores the minimum and maximum values of the whole numbers as before and is assigned a value once.

Now let’s imagine that the calculator app also determines if a particular whole number is either even or odd.

There are two print function calls in the code. This logic can be simplified using ternary operators.

The code now uses the remainder operator to check the whole number’s parity. The entire logic is encapsulated inside one print function call.

You have only converted simple if-else statements to ternary operator statements so far. Next, we’ll look at how to convert nested if-else statements to multiple ternary operator statements.

You can use a nested if-else statement to determine the full name of a specific person from their first and last names.

The code covers all of the possible cases. The values of the constants of the first and last names can be empty strings or not. The name constant is therefore assigned values four times.

You can simplify this logic with multiple ternary operators .

The name constant is assigned a value once. The assignment is indented on multiple lines, making it easy to read and understand.

In this article, I have highlighted the most common use cases of the ternary operator in Swift. The most important thing to remember is that you can always revert to equivalent if-else statements if and only if the ternary operator statements don’t work as expected in your code.

It's easy to make an app by throwing some code together. But without best practices and robust architecture, you soon end up with unmanageable spaghetti code. In this guide I'll show you how to properly structure SwiftUI apps.

swift ternary operator assignment

Cosmin has been writing tutorials and books on Swift and iOS development since 2014, when the first version of Swift was released. He has been part of influential iOS development communities such as raywenderlich.com and appcoda.com since 2010 and has taught iOS development with Objective-C and Swift since 2012. Cosmin lives in Romania and has engineering degrees in electronics, telecommunications, neural networks, microprocessors, microcontrollers, distributed systems, and web technologies from the technical universities of Cluj-Napoca and Iași. He has worked with many programming languages over the years, but none of them has had such a significant impact on himself as Swift. Cosmin likes to play the guitar or study WW2 history when not coding

Leave a Comment Cancel reply

The Swift Handbook – Learn Swift for Beginners

  • Introduction to Swift

The Swift programming language was created by Apple in 2014. It's the official language that works with the whole Apple Operating Systems lineup: iOS, iPadOS, watchOS, macOS, and tvOS.

Swift is an open source, general purpose, compiled programming language that's statically typed.

Every value has a type assigned. The type of a value is always checked when used as an argument or returned, at compile time. If there is a mismatch, the program will not compile.

Swift's compiler is LLVM, and it is included within Xcode, the standard IDE you use for Apple software development.

Swift is a modern programming language that was designed to "fit" in an ecosystem that was previously designed for a different programming language called Objective-C.

Most of the software running on the iPhone and Mac today is based on Objective-C code, even for official Apple apps. But Swift usage is gaining traction year after year. While Objective-C will be used for years to maintain and improve existing apps, new applications are likely going to be created with Swift.

Before Apple introduced Swift, Objective-C was heavily developed to introduce new capabilities and features. But in the recent years this effort has decreased a lot in favor of Swift development.

This does not mean Objective-C is dead or not worth learning: Objective-C is still an essential tool for any Apple developer.

That said, I am not going to cover Objective-C here, because we're focusing on Swift – the present and future of the Apple platform.

In just 6 years, Swift has gone through 5 major versions, and we're now (at the time of writing) at version 5.

Swift is famously Apple's products language, but it is not an Apple-only language. You can use it on several other platforms.

It is open source, so porting the language to other platforms does not require any permission or licensing, and you can find Swift projects to create Web servers and APIs ( https://github.com/vapor/vapor ) as well as projects to interact with microcontrollers.

Swift is a general-purpose language, built with modern concepts, and it has a bright future.

What We'll Cover Here

The goal of this book is to get you up and running with Swift, starting from zero.

If you have a Mac or an iPad, I recommend you to download the Playgrounds application made by Apple from the App Store.

This app lets you run snippets of Swift code without having to create a full app first. It's a very handy way to test your code, not just when you start learning, but whenever you need to try some code.

It also contains a series of awesome examples and tutorials to expand your Swift and iOS knowledge.

Note: You can get a PDF and ePub version of this Swift Beginner's Handbook

Variables in Swift

Objects in swift, operators in swift, conditionals in swift, loops in swift, how to write comments in swift, semicolons in swift, numbers in swift, strings in swift, booleans in swift, arrays in swift, sets in swift, dictionaries in swift, tuples in swift, optionals and nil in swift, enumerations in swift, structures in swift, classes in swift, functions in swift, protocols in swift, where to go from here.

Variables let us assign a value to a label. We define them using the var keyword:

Once a variable is defined, we can change its value:

Variables that you do not want to change can be defined as constants, using the let keyword:

Changing the value of a constant is forbidden.

Screen-Shot-2020-11-01-at-07.51.48

When you define a variable and you assign it a value, Swift implicitly infers the type of it.

8 is an Int value.

"Roger" is a String value.

A decimal number like 3.14 is a Double value.

You can also specify the type at initialization time:

But it's typical to let Swift infer it, and it's mostly done when you declare a variable without initializing it.

You can declare a constant, and initialize it later:

Once a variable is defined, it is bound to that type. You cannot assign to it a different type, unless you explicitly convert it.

You can't do this:

Screen-Shot-2020-11-01-at-07.54.25

Int and String are just two of the built-in data types provided by Swift.

In Swift, everything is an object. Even the 8 value we assigned to the age variable is an object.

In some languages, objects are a special type. But in Swift, everything is an object and this leads to one particular feature: every value can receive messages .

Each type can have multiple functions associated to it, which we call methods .

For example, talking about the 8 number value, we can call its isMultiple method, to check if the number is a multiple of another number:

Screen-Shot-2020-11-01-at-14.43.49

A String value has another set of methods.

A type also has instance variables. For example the String type has the instance variable count , which gives you the number of characters in a string:

Screen-Shot-2020-11-01-at-14.45.39

Swift has 3 different object types , which we'll see more in details later on: classes , structs and enums .

Those are very different, but they have one thing in common: to object type, we can add methods , and to any value, of any object type, we can send messages .

We can use a wide set of operators to operate on values.

We can divide operators in many categories. The first is the number of targets: 1 for unary operators , 2 for binary operators or 3 for the one and only ternary operator .

Then we can divide operators based on the kind of operation they perform:

  • assignment operator
  • arithmetic operators
  • compound assignment operators
  • comparison operators
  • range operators
  • logical operators

plus some more advanced ones, including nil-coalescing, ternary conditional, overflow, bitwise and pointwise operators.

Note: Swift allows you to create your own operators and define how operators work on your types you define.

Assignment operator in Swift

You use the assignment operator to assign a value to a variable:

Or to assign a variable value to another variable:

Arithmetic operators in Swift

Swift has a number of binary arithmetic operators: + , - , * , / (division), % (remainder):

- also works as a unary minus operator:

You can also use + to concatenate String values:

Compound assignment operators in Swift

The compound assignment operators combine the assignment operator with arithmetic operators:

Comparison operators in Swift

Swift defines a few comparison operators:

You can use those operators to get a boolean value ( true or false ) depending on the result:

Range operators in Swift

Range operators are used in loops. They allow us to define a range:

Here's a sample usage:

Logical operators in Swift

Swift gives us the following logical operators:

  • ! , the unary operator NOT
  • && , the binary operator AND
  • || , the binary operator OR

Sample usage:

Those are mostly used in the if conditional expression evaluation:

if statements in Swift

if statements are the most popular way to perform a conditional check. We use the if keyword followed by a boolean expression, followed by a block containing code that is run if the condition is true:

An else block is executed if the condition is false:

You can optionally wrap the condition validation into parentheses if you prefer:

And you can also just write:

One thing that separates Swift from many other languages is that it prevents bugs caused by erroneously doing an assignment instead of a comparison. This means you can't do this:

The reason is that the assignment operator does not return anything, but the if conditional must be a boolean expression.

switch statements in Swift

Switch statements are a handy way to create a conditional with multiple options:

When the code of a case ends, the switch exits automatically.

A switch in Swift needs to cover all cases. If the tag , name in this case, is a string that can have any value, we need to add a default case, mandatory.

Otherwise with an enumeration, you can simply list all the options:

A case can be a Range:

Ternary conditional operator in Swift

The ternary conditional operator is a shorter version of an if expression. It allows us to execute an expression if a condition is true, and another expression if the condition is false.

Here is the syntax:

The syntax is shorter than an if statement, and sometimes it might make more sense to use it.

for-in loops in Swift

You can use for-in loops to iterate a specific amount of times, using a range operator:

You can iterate over the elements of an array or set:

And on the elements of a dictionary:

while loops in Swift

A while loop can be used to iterate on anything, and will run while the condition is true :

The condition is checked at the start, before the loop block is executed.

repeat-while loops in Swift

A repeat-while loop in Swift is similar to the while loop. But in this case the condition is checked at the end, after the loop block, so the loop block is executed at least once. Then the condition is checked, and if it is evaluated as true , the loop block is repeated:

How to use Swift's ternary operator

How to use Swift's ternary operator image

What is a Ternary Operator?

The ternary operator is a concise way of making a decision in your code by asking a question, then running different code depending on the answer. It is called a 'ternary' operator because it takes three operands - a condition, a result for true, and a result for false.

Using the Swift Ternary Operator

In Swift, the ternary operator is represented as condition ? valueIfTrue : valueIfFalse . Below, we'll walk you through how to use this powerful operator.

Step 1: Defining the Condition

The first part of the ternary operator is the condition. This is a statement that can be evaluated to either true or false. For example:

In this case, the condition isRaining is true.

Step 2: Providing Responses for Both Outcomes

The next step is to provide two outcomes: one for when the condition is true, and one for when it is false. Here's how:

If isRaining is true, the message will be "Take an umbrella". If it's false, the message will be "Enjoy the sun".

When to Use the Ternary Operator?

The ternary operator is best used when you want to choose between two simple, related expressions based on a condition. It's a more concise, readable alternative to an if-else statement.

As you can see, the Swift ternary operator is a powerful tool that can help you write clean, efficient code. If you're planning to hire Swift developers , make sure they understand and can effectively use these advanced Swift features.

If you're interested in enhancing this article or becoming a contributing author, we'd love to hear from you.

Please contact Sasha at [email protected] to discuss the opportunity further or to inquire about adding a direct link to your resource. We welcome your collaboration and contributions!

Ternary Operator

A ternary operator , also known as a conditional operator, is a type of operator that takes three arguments. The first argument is a comparison or logical statement that returns either true or false. The second and third arguments are the two possible results of this statement. In other words, it evaluates an expression and then returns one value if that expression is true and another value if the expression is false, thus making the code more compact and concise.

Empower Your Tech Team with Remote Database and Ruby Developers Skilled in Slack API

Expand Your Engineering Capabilities with Expert Remote Ruby Developers and Database Specialists Skilled in Amazon API

Elevate Your Tech Team with Expert Remote Developers in Databases, Ruby, and Docker Swarm

secure.food

This page requires JavaScript.

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

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

Do you know everything about Swift?

You don't need to master everything, but staying informed is crucial. Join our community of 17,372 developers and stay ahead of the curve:

Featured SwiftLee Jobs

  • Mobile Software Engineer @ Stan

Find your next Swift career step at world-class companies with impressive apps by joining the SwiftLee Talent Collective. I'll match engineers in my collective with exciting app development companies. SwiftLee Jobs

  • Import Module
  • Variable Declaration
  • Dictionaries
  • Enumerations
  • If Statement
  • Switch Case
  • For In Loop
  • Repeat-While Loop
  • Ternary Operator
  • Class Declaration
  • Access Modifiers
  • Initializer
  • Instantiation
  • Type Methods
  • Getters and Setters
  • Inheritance

Control Flow

Ternary operator in swift.

The ternary operator is used to execute code based on the result of a binary condition.

It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a method.

The ternary is strictly an assignment operator (cannot be used to execute expressions).

The Swift Programming Language - Basic Operators

Add to Slack

Learn Python practically and Get Certified .

Popular Tutorials

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

  • Swift Hello World
  • Swift Variables and Constants
  • Swift Data Types
  • Swift Characters & Strings
  • Swift Input and Output
  • Swift Expressions & Statements
  • Swift Comments
  • Swift Optionals

Swift Operators

  • Swift Operator Precedence
  • Swift Ternary Operator
  • Swift Bitwise Operators

Swift Flow Control

  • Swift if...else statement
  • Swift switch Statement
  • Swift for-in Loop
  • Swift while & repeat while loop
  • Swift Nested Loops
  • Swift break Statement
  • Swift continue Statement
  • Swift guard Statement

Swift Collections

  • Swift Arrays
  • Swift Dictionary
  • Swift Tuples
  • Swift Functions
  • Swift Function Parameters
  • Swift Nested Functions
  • Swift Recursion
  • Swift Ranges
  • Swift Function Overloading
  • Swift Closures
  • Swift Class and Objects
  • Swift Properties
  • Swift Methods
  • Swift Initializer
  • Swift Deinitialization
  • Swift Inheritance
  • Swift Overriding
  • Swift Protocols

Swift Enum & Struct

  • Swift Enum Associated Value
  • Swift Structs
  • Swift Singleton

Swift Additional Topics

  • Swift Error Handling
  • Swift Generics
  • Swift Extension
  • Swift Access Control
  • Swift Type Alias
  • Swift Hashable
  • Swift Equatable
  • Swift Strong Weak Reference

Swift Tutorials

Swift Bitwise and Bit Shift Operators

Swift Ternary Conditional Operator

Swift Expressions, Statements and Code blocks

Swift Operator precedence and associativity

Operator precedence is a set of rules that determines which operator is executed first.

Before you learn about operator precedence, make sure to know about Swift operators .

Let's take an example, suppose there is more than one operator in an expression.

  • if + is executed first, the value of num will be 52
  • if * is executed first, the value of num will be 28

In this case, operator precedence is used to identify which operator is executed first. The operator precedence of * is higher than + so multiplication is executed first.

  • Operator precedence table

The table below lists the precedence of Swift operators. The higher it appears in the table, the higher its precedence.

  • Example: Operator precedence with the complex assignment operator

In the above example, we have created a variable num with the value 15 . Notice the statement

num += 10 - 2 * 3

Here, the precedence order from higher to lower is * , - , and += . Hence, the statement is executed as num += 10 - (2 * 3) .

  • Swift Operator Associativity

If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left). For example,

Here, operators * and / have the same precedence. And, their associativity is from left to right. Hence, 6 * 4 is executed first.

Note: If we want to execute the division first, we can use parentheses as print(6 * (4/3)) .

  • Operator Associativity Table

If an expression has two operators with similar precedence, the expression is evaluated according to its associativity.

  • Left Associativity - operators are evaluated from left to right
  • Right Associativity - operators are evaluated from right to left
  • Non-associativity - operators have no defined behavior

For example,

Here, operators * and / have the same precedence. However, their associativity is left. Hence, 6 * 4 is executed first.

The table below shows the associativity of Swift operators.

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

Swift Tutorial

Swift Programming and iOS Development

A site for Swift Programming and iOS Development.

  • Introduction to Swift
  • Introduction to iOS Develpment
  • Reference Guide

Wednesday, November 22, 2017

Swift 4 book i chapter 3: swift basic operators, chapter 3: swift basic operators.

  • Unary Operator: Unary operator works with a single operand. It can be placed in front of an operand (prefix) or placed behind an operand (postfix). Examples of prefix unary operator are -variable1, -10 and !variable2. Example of postfix unary operator is variable3!   
  • Binary Operator: Binary operator works in between 2 operand. Examples of binary operator are a + b, c / d and e * f
  • Ternary Operator: Ternary operator works with 3 operand. There is only one ternary operator in Swift; it is the ternary conditional operator (a ? b : c)

Assignment Operator

swift ternary operator assignment

Assignment Operator Do Not Return Value

Arithmetic operator.

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

swift ternary operator assignment

  • Please use floating point for division to get accurate result.
  • Please note that any number divide by zero will return error

swift ternary operator assignment

Remainder Operator

swift ternary operator assignment

Rules of Remainder Operator

Remainder operator with negative number.

swift ternary operator assignment

Modulus and Remainder Operator

swift ternary operator assignment

Remainder for Floating Point Number

swift ternary operator assignment

Unary Minus Operator

swift ternary operator assignment

Application of Arithmetic Operator

swift ternary operator assignment

Compound Assignment Operator

  • Addition (+=) same as a = a + x
  • Subtraction (-=) same as a = a - x
  • Multiplication (*=) same as a = a * x
  • Division (/=) same as a = a / x
  • Remainder (%=) same as a = a % x

swift ternary operator assignment

Comparison Operator

  • Not Equal (!=)
  • Greater than (>)
  • Less than (<)
  • Greater than OR Equal to (>=)
  • Less than OR Equal to (<=)

swift ternary operator assignment

Boolean for C Programmer

swift ternary operator assignment

Ternary Conditional Operator

swift ternary operator assignment

Range Operator

Closed range operator.

swift ternary operator assignment

Application of Close Range Operator

swift ternary operator assignment

Half-Open Range Operator

swift ternary operator assignment

One-Sided Range Operator

One-sided close range operator.

swift ternary operator assignment

One-Sided Half Open Range Operator

swift ternary operator assignment

Logical Operator

  • NOT operator is denoted as !
  • AND operator is denoted as &&
  • OR operator is denoted as ||

Logical NOT Operator

swift ternary operator assignment

Logical AND Operator

swift ternary operator assignment

Logical OR Operator

swift ternary operator assignment

Compound Logical Operator

swift ternary operator assignment

Operator Precedence

swift ternary operator assignment

Explicit Parentheses

swift ternary operator assignment

No comments:

Post a comment.

How to create custom operators and do operators overloading in Swift

What is the operator.

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

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

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

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

swift ternary operator assignment

Turn your code into a snapshot: Codeshot creates a beautiful image of your code snippets. Perfect size for Twitter.

Types of operators

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

Unary operators

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

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

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

Binary operators

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

We can overload and create a custom infix operator.

Ternary operators

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

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

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

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

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

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

Overloading the existing operators

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

Let's start with overloading infix operators.

Overload new operator on strings

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

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

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

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

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

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

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

Again, here is the result:

Overload existing operators with different arguments.

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

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

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

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

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

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

And here is the result:

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

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

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

Adding a custom operator

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

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

This is a syntax to declare a new infix operator.

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

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

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

This is a syntax to declare a new postfix operator.

Then we use it just like before.

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

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

And here is how we implement it.

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

The difference between overload existing operator and a custom one

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

Operator implementation without matching operator declaration error

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

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

Related Resourcess

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

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

You may also like

  • What does the ?? operator mean in Swift 30 Sep 2021
  • Swift Ternary operator (?:) 09 Feb 2023
  • Swift private access level change in Swift 4 07 Feb 2023
  • Swift fileprivate vs private 09 Mar 2023
  • Sign in with Apple Tutorial, Part 2: Private Email Relay Service 22 Dec 2019
  • How to make parts of Text view Bold in SwiftUI 23 Nov 2022

Enjoy the read?

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

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

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

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

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

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

ternary operator ?: suggestion

The current ternary operator, for this example:

let val = p == 5 ? 10 : 40

Which I have always thought was hard to read but I do like the functionality it provides. That is, in one expression you can compactly get two different values based upon a condition. Swift seems to have adopted the C style ternary operators probably to not completly change everytihg. Similar to the drop of the ++ and -- operator I am proposing that there is to replace the ternary operator to improve readability but continue to provide that functionality.

Recommendation: most readable but changes rules about if-else always having braces and puts the “if” at end. It is only a little bit longer than the original. I think it is clearer to have the conditional at the end so the assignment part is where the variable is assigned. This also does not introduce new keywords or operators.

let val = 10 else 40 if p == 5

In looking at the Nil-Coalescing operator there is a similar idea but it is really not the same. In that the left hand side of the ?? operator returns itself when non nil, and the behavior of the ternary operator is different. It is also harder to read.

let val = 10 ?? 40 if p = 5

I also considered a bunch of other possibilities like using “where" or “when" instead of “if”, the python of putting conditional in the middle or the ruby style of “if" returning a value but did not like those.

// python style let val = 10 if p == 5 else 40

// ruby style let val = if p == 5 then 10 else 40

Hmm… that is really interesting. I wonder if we can use optionals to make this work in an elegant way.

Forget about else for a second. What if there is an operation which says, this is either this value or nil based on whether it meets a condition? Then else (and else if) can be handled by a combination of that operation and the nil-coelecing operator.

I once wrote a small DSL which had this behavior and it was really nice.

What about something like:

  let x = value if? condition

x would have value if condition evaluates to true, or it would be nil. If I wanted an else statement:

  let x = value if? condition ?? otherValue

Now it works just like the ternary operator, but is IMHO more readable. Note: these can also be chained to give you else if style behavior:

  let x = value if? condition ?? otherValue if? otherCondition ?? evenMoreValue

You could optionally (ha!) put things in parentheses as well, which I always end up doing with the ternary:

  let x = (value if? condition) ?? (otherValue if? otherCondition) ?? evenMoreValue

Not a 100% there yet, but I do think it is a good start at something more elegant…

Thanks, Jon

On Dec 5, 2015, at 10:29 AM, possen p <[email protected]> wrote: The current ternary operator, for this example: let val = p == 5 ? 10 : 40 Which I have always thought was hard to read but I do like the functionality it provides. That is, in one expression you can compactly get two different values based upon a condition. Swift seems to have adopted the C style ternary operators probably to not completly change everytihg. Similar to the drop of the ++ and -- operator I am proposing that there is to replace the ternary operator to improve readability but continue to provide that functionality. Recommendation: most readable but changes rules about if-else always having braces and puts the “if” at end. It is only a little bit longer than the original. I think it is clearer to have the conditional at the end so the assignment part is where the variable is assigned. This also does not introduce new keywords or operators. let val = 10 else 40 if p == 5 In looking at the Nil-Coalescing operator there is a similar idea but it is really not the same. In that the left hand side of the ?? operator returns itself when non nil, and the behavior of the ternary operator is different. It is also harder to read. let val = 10 ?? 40 if p = 5 I also considered a bunch of other possibilities like using “where" or “when" instead of “if”, the python of putting conditional in the middle or the ruby style of “if" returning a value but did not like those. // python style let val = 10 if p == 5 else 40 // ruby style let val = if p == 5 then 10 else 40 _______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution

IMAGES

  1. How to use the ternary conditional operator for quick tests

    swift ternary operator assignment

  2. Swift Ternary Conditional Operator (With Examples)

    swift ternary operator assignment

  3. Swift Programming Tutorial

    swift ternary operator assignment

  4. Swift for Beginners Part 20

    swift ternary operator assignment

  5. Tutorial Swift

    swift ternary operator assignment

  6. 10 Examples Of Ternary Operator In Java

    swift ternary operator assignment

VIDEO

  1. iOS Swift lesson 8

  2. Swift Programming Tutorials In Hindi

  3. operator

  4. 6_Operator Assignment Relational LogicalBitwise

  5. CombineLatest in swift

  6. DAY 001

COMMENTS

  1. Swift Ternary Conditional Operator (With Examples)

    Ternary Operator in Swift. A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is. if condition is true, expression1 is executed. if condition is false, expression2 is executed. The ternary operator takes 3 operands ( condition, expression1, and expression2 ). Hence, the name ternary operator.

  2. How to use the ternary conditional operator for quick tests

    There's one last way to check conditions in Swift, and when you'll see it chances are you'll wonder when it's useful. To be fair, for a long time I very rarely used this approach, but as you'll see later it's really important with SwiftUI. This option is called the ternary conditional operator.

  3. Assign conditional expression in Swift?

    Note 1: I do NOT want to have to use the ternary operator for this). 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. You can't do that ...

  4. Write Shorter Conditions with the Swift Ternary Operator

    The assignment is indented on multiple lines, making it easy to read and understand. Conclusion. In this article, I have highlighted the most common use cases of the ternary operator in Swift. The most important thing to remember is that you can always revert to equivalent if-else statements if and only if the ternary operator statements don ...

  5. The Swift Handbook

    plus some more advanced ones, including nil-coalescing, ternary conditional, overflow, bitwise and pointwise operators. Note: Swift allows you to create your own operators and define how operators work on your types you define. Assignment operator in Swift. You use the assignment operator to assign a value to a variable: var age = 8

  6. The ternary operator

    The ternary operator. Swift has a rarely used operator called the ternary operator. It works with three values at once, which is where its name comes from: it checks a condition specified in the first value, and if it's true returns the second value, but if it's false returns the third value. The ternary operator is a condition plus true or ...

  7. How to use Swift's ternary operator

    It is called a 'ternary' operator because it takes three operands - a condition, a result for true, and a result for false. Using the Swift Ternary Operator. In Swift, the ternary operator is represented as condition ? valueIfTrue : valueIfFalse. Below, we'll walk you through how to use this powerful operator. Step 1: Defining the Condition

  8. Basic Operators

    Basic Operators. Perform operations like assignment, arithmetic, and comparison. An operator is a special symbol or phrase that you use to check, change, or combine values. For example, the addition operator ( +) adds two numbers, as in let i = 1 + 2, and the logical AND operator ( &&) combines two Boolean values, as in if enteredDoorCode ...

  9. Advanced Operators

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

  10. How To Create an Operator in Swift

    Assignment operator — An operator that updates the value (e.g. num += 1). Ternary operator — An operator with two symbols with three expressions (e.g. condition ? true_expression : false_expression). In Swift, every operator type except the ternary operator is customizable. This means you can create a new custom operator.

  11. Custom Operators in Swift with practical code examples

    Examples of basic operators available in Swift. To fully understand what operators are we can go over a few operator examples that are available in Swift by default. Some might be more obvious to you than others! For example, the assignment operator is very often used (obviously) but is also an operator! /// Assignment `=` operator example. let ...

  12. Ternary Operator in Swift

    Ternary Operator in Swift. The ternary operator is used to execute code based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a method.

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

  14. How to use ternary operator in Swift

    I want to use ternary operator in func printThis(_ items: Any...) import Foundation class PrintHelper { /// This will help us to stop printing any thing to the console if we want at any time to look for something important. static var printIsAllowed: Bool { return true // set false to stop printing ..

  15. Swift Operator precedence and associativity (With Examples)

    Swift Operator Associativity. If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left). For example, print(6 * 4 / 3) // 8. Here, operators * and / have the same precedence. And, their associativity is from left to right.

  16. Swift 4 Book I Chapter 3: Swift Basic Operators

    There is only one ternary operator in Swift; it is the ternary conditional operator (a ? b : c) In a statement 1 + 2, the plus sign is the operator and the numbers are operands. Assignment Operator. ... Swift assignment operator does not return a number or boolean value.

  17. Can't use `if case` with Ternary Operator?

    The question is very clear. Unfortunately, there is no such feature in Swift. You simply have to do the pattern matching with if case, guard case, or in a switch. There has been plenty of discussion here about how to design such a feature to match cases without also comparing the associated values, but such a feature does not exist today. (If ...

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

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

  19. how to overload an assignment operator in swift

    You can not override assignment but you can use different operators in your case. For example &= operator. func &= (inout left: CGFloat, right: Float) { left = CGFloat (right) } So you could do the following: var A: CGFLoat = 1 var B: Float = 2 A &= B. By the way operators &+, &-, &* exist in swift. They represent C-style operation without ...

  20. ternary operator ?: suggestion

    The current ternary operator, for this example: let val = p == 5 ? 10 : 40 Which I have always thought was hard to read but I do like the functionality it provides. That is, in one expression you can compactly get two different values based upon a condition. Swift seems to have adopted the C style ternary operators probably to not completly change everytihg. Similar to the drop of the ++ and ...

  21. swift: about ternary operator Question. Why my code is error code

    In Swift, the ternary condition operator is an expression which takes the form <condition> ? <expression if true> : <expression if false> Expressions are part of larger statements, and the ternary specifically is one which evaluates to either the expression after the ?, or the one after the : depending on the truth of the condition.. continue, however, is not an expression but a statement on ...