This page requires JavaScript.

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

Conditionals & Logic

Print Cheatsheet

if Statement

An if statement executes a code block when its condition evaluates to true . If the condition is false , the code block does not execute.

else Statement

An else statement is a partner to an if statement. When the condition for the if statement evaluates to false , the code within the body of the else will execute.

else if Statement

An else if statement provides additional conditions to check for within a standard if / else statement. else if statements can be chained and exist only after an if statement and before an else .

Comparison Operators

Comparison operators compare the values of two operands and return a Boolean result:

  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to
  • == equal to
  • != not equal to

Ternary Conditional Operator

The ternary conditional operator, denoted by a ? , creates a shorter alternative to a standard if / else statement. It evaluates a single condition and if true , executes the code before the : . If the condition is false , the code following the : is executed.

switch Statement

The switch statement is a type of conditional used to check the value of an expression against multiple cases. A case executes when it matches the value of the expression. When there are no matches between the case statements and the expression, the default statement executes.

switch Statement: Interval Matching

Intervals within a switch statement’s case provide a range of values that are checked against an expression.

switch Statement: Compound Cases

A compound case within a switch statement is a single case that contains multiple values. These values are all checked against the switch statement’s expression and are separated by commas.

switch Statement: where Clause

Within a switch statement, a where clause is used to test additional conditions against an expression.

Logical Operator !

The logical NOT operator, denoted by a ! , is a prefix operator that negates the value on which it is prepended. It returns false when the original value is true and returns true when the original value is false .

Logical Operator &&

The logical AND operator, denoted by an && , evaluates two operands and returns a Boolean result. It returns true when both operands are true and returns false when at least one operand is false .

Logical Operator ||

The logical OR operator, denoted by || , evaluates two operands and returns a Boolean result. It returns false when both operands are false and returns true when at least one operand is true .

Combining Logical Operators

Logical operators can be chained in order to create more complex logical expressions. When logical operators are chained, it’s important to note that the && operator has a higher precedence over the || operator and will get evaluated first.

Controlling Order of Execution

Within a Swift logical expression, parentheses, () , can be used to organize and control the flow of operations. The usage of parentheses within a logical expression overrides operator precedence rules and improves code readability.

Learn More on Codecademy

Learn swift: conditionals and loops, learn swift.

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

 

Conditional statements

Sometimes you want code to execute only if a certain condition is true, and in Swift that is represented primarily by the if and else statements. You give Swift a condition to check, then a block of code to execute if that condition is true.

You can optionally also write else and provide a block of code to execute if the condition is false, or even else if and have more conditions. A "block" of code is just a chunk of code marked with an open brace – { – at its start and a close brace – } – at its end.

Here's a basic example:

Using a condition to conditionally assign a value.

That uses the == (equality) operator introduced previously to check whether the string inside person is exactly equivalent to the string "hater". If it is, it sets the action variable to "hate". Note that open and close braces, also known by their less technical name of "curly brackets" – that marks the start and end of the code that will be executed if the condition is true.

Let's add else if and else blocks:

A conditional with three branches. Only one is executed.

That will check each condition in order, and only one of the blocks will be executed: a person is either a hater, a player, or anything else.

Evaluating multiple conditions

You can ask Swift to evaluate as many conditions as you want, but they all need to be true in order for Swift to execute the block of code. To check multiple conditions, use the && operator – it means "and". For example:

A conditional which checks if both conditions are true.

Because stayOutTooLate and nothingInBrain are both true, the whole condition is true, and action gets set to "cruise." Swift uses something called short-circuit evaluation to boost performance: if it is evaluating multiple things that all need to be true, and the first one is false, it doesn't even bother evaluating the rest.

Looking for the opposite of truth

This might sound deeply philosophical, but actually this is important: sometimes you care whether a condition is not true, i.e. is false. You can do this with the ! (not) operator that was introduced earlier. For example:

A conditional which checks if both conditions are false.

This time, the action variable will only be set if both stayOutTooLate and nothingInBrain are false – the ! has flipped them around.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

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

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

 

Buy Pro Swift

Was this page useful? Let us know!

Average rating: 4.6/5

Unknown user

You are not logged in

Link copied to your pasteboard.

Use if/else and switch statements as expressions in Swift 5.9

Schurigeln

Swift 5.9 brought an arsenal of enhancements to the already powerful and versatile language, but there's one in particular that has been long anticipated by developers. Swift now allows the use of if/else and switch statements as expressions, presenting an avenue to write more readable and concise code. This feature is a game-changer in initializing variables based on complex conditions without resorting to difficult-to-read ternary expressions.

If/Else Statements as Expressions

Consider the situation where you want to initialize a let variable based on a complex condition. Traditionally, this would necessitate using compound ternary expressions that can quickly become convoluted. Here's an example of what that may look like:

Now, with Swift 5.9, you can leverage if/else expressions. This allows you to use a more familiar and readable chain of if statements. Below is the transformed code:

The updated code is considerably more readable and easier to follow, enhancing the overall maintainability of the codebase.

Global Variables and Stored Properties

The ability to use if/else and switch statements as expressions is particularly useful when initializing a global variable or a stored property. In previous versions of Swift, if your initialization required complex conditionals or switch statements, you would need to wrap them in a closure and execute it immediately, as shown:

Now, with the power of if expressions, you can simply eliminate that clutter, leaving you with much neater code:

Swift 5.9 brings a significant enhancement in readability and conciseness by allowing if/else and switch statements to be used as expressions. This can drastically improve your code structure, making it easier to read, understand, and maintain.

Happy coding!

XOXO, Christian 👨🏻‍💻

Swift by Sundell

Articles, podcasts and news about Swift development, by John Sundell .

Conditional compilation within Swift expressions

  • language features

New in Swift 5.5: It’s now possible to conditionally compile postfix member expressions using Swift’s #if compiler directive . Let’s take a look at what kinds of situations that this new feature could be really useful in.

Working around platform differences

Although many of the built-in APIs and frameworks work exactly the same way across Apple’s platforms, there are certain differences that we might need to work around. For example, when using SwiftUI to build an app that runs on both iOS and the Mac, we might find ourselves in the following type of situation — in which we’re getting an error when attempting to apply the iOS-specific InsetGroupedListStyle to a List :

In general, these kinds of issues can be worked around using a compile-time platform check — but before Swift 5.5, we’d have to first break our List out into a separate expression, and then apply different listStyle modifiers separately using an #if -based operating system condition:

In isolation, the above code doesn’t look that bad , but if our ItemList view were to gain additional subviews (or if we’d need to perform additional compile-time checks within it), then its body could quickly become quite hard to read.

So perhaps a more robust solution to this problem would be to instead extract the above platform check into a dedicated modifier method — for example like this:

With the above in place, we can simply apply our new defaultListStyle modifier within our ItemList view, and we no longer have to deal with any platform differences when constructing our actual UI:

However, while the above is certainly a neat technique when working with modifiers and styles that we’re looking to reuse multiple times across a project, always having to define a dedicated method each time we encounter a platform difference can become quite tedious.

This is where Swift 5.5’s new support for #if conditions within postfix member expressions comes in.

Inline checks within expressions

When using Swift 5.5, we now have the option to inline #if directives right within our expressions. So, going back to our ItemList , we can now conditionally apply each of our listStyle modifiers completely inline — without first having to break our expression up into multiple parts:

Above we’re also making use of another new language feature that enables us to refer to SwiftUI list styles (and other kinds of protocol-based types) using dot syntax. Check out “Using static protocol APIs to create conforming instances” to learn more about that.

Nice! Of course, this new capability also works for other kinds of #if -based compile-time checks — including using the standard DEBUG flag to check if our app is being compiled using its debug build configuration, and any custom compiler flags that we might’ve defined.

As an example, here’s how we could use a custom flag to conditionally visualize the final rendering size of one of our views:

To learn more about how to define and use custom compiler flags, check out “Using compiler directives in Swift” .

So, how should we pick between these new inline #if conditions versus creating dedicated modifiers for working around platform differences and for performing other kinds of compile-time checks? While every developer will certainly have their own preferences — for me, it all depends on whether a given pattern will be repeated within a code base, or whether it’s something that we’re only performing once.

For repeated compile-time checks, I still prefer to create dedicated functions, since that lets me wrap those checks up into a much simpler API, but when working around minor platform differences (like we did above), I prefer the new inline style. It’s already proving to be quite useful when working on cross-platform SwiftUI-based projects.

If you have any questions, comments, or feedback, then feel free to reach out via email .

Thanks for reading!

  • Share this article on Twitter

More on similar topics

Capturing objects in swift closures, throwing and asynchronous swift properties, using tuples as lightweight types in swift.

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Swift Tutorials
  • Swift Tutorial
  • Swift Comments
  • Swift If-Else
  • Swift Switch
  • ADVERTISEMENT
  • Swift Ternary Operator
  • Swift If AND
  • Swift If OR
  • Swift If NOT
  • Swift Addition
  • Swift Subtraction
  • Swift Multiplication
  • Swift Division
  • Swift Modulus Division
  • Swift Assignment
  • Swift Addition Assignment
  • Swift Subtraction Assignment
  • Swift Multiplication Assignment
  • Swift Division Assignment
  • Swift Modulus Assignment
  • Swift For Loop
  • Swift While Loop
  • Swift Repeat While Loop
  • Swift Break
  • Swift Continue
  • Swift Infinite While Loop
  • Swift – Function with parameters
  • Swift – Function with multiple parameters
  • Swift – Call function with no parameter labels
  • Swift – Custom label for function parameters
  • Swift – Assign default value for parameters in function
  • Swift – Pass Parameter by Reference to Function
  • Swift – Assign function to a variable
  • Swift – Pass function as parameter
  • Swift – Return function from another function
  • Swift – Function to find sum of one or more integers
  • String Basics
  • Swift – Create a string variable
  • Swift – Create an empty string
  • Swift – Multiline strings
  • Swift – String Length
  • Swift – Append a String to Another String
  • Swift – Concatenate Strings
  • Swift – Compare Strings
  • Swift – Include Double Quotes in String
  • Swift – Include Value of Variable in String
  • Swift – Loop over Characters in String
  • Swift – Substring
  • String Checks
  • Swift – Check if two Strings are Equal
  • Swift – Check if two Strings are not Equal
  • Swift – Check if String is Empty
  • Swift – Check if String contains SubString
  • Swift – Check if String starts with a Specific Prefix
  • Swift – Check if String ends with a Specific Suffix
  • Swift – Check if Variable Type is String Programmatically
  • Transformations / Modifications
  • Swift – Convert String to Lowercase
  • Swift – Convert String to Uppercase
  • Swift – Insert Character at Specific Index in String
  • Swift – Remove Character at Specific Index in String
  • Swift – Remove Last Character of String
  • Swift – Remove Specific Characters from String
  • Swift – Reverse String
  • Swift – Split String by Character
  • String Conversions
  • Swift – Convert String to Integer
  • Swift – Convert Integer to String
  • Array Basics
  • Swift – Create Empty Array
  • Swift – Create Empty String Array
  • Swift – Create an Array of Specific Size
  • Swift – Create an Array with Default Value for Each Item
  • Swift – Create an Array with Initial Values
  • Swift – Initialize Array
  • Swift – Initialize Array with Different Type Values
  • Swift – Integer Array
  • Swift – String Array
  • Swift – Print Array
  • Swift – Get Array Size
  • Swift – Get Array as String
  • Access Arrays
  • Swift – Access Elements of Array using Index
  • Swift – Get First Element of Array
  • Swift – Get Last Element of Array
  • Swift – Get Random Element from Array
  • Swift – Array forEach()
  • Swift – Loop over Array using For Loop
  • Swift – Loop over Array using While Loop
  • Swift – Loop over Array using forEach Loop
  • Array Checks
  • Swift – Check if an Array is Empty
  • Swift – Check if Array contains Specific Element
  • Swift – Check if String Array contains a Specific String
  • Swift – Check if Two Arrays are Equal
  • Find in Arrays
  • Swift – Find Index of Specific Element in Array
  • Swift – Find Minimum Element of Array
  • Swift – Find Maximum Element of Array
  • Arrays Modify / Transform
  • Swift – Append an Element to Array
  • Swift – Append an Array to Another Array
  • Swift – Append an integer to Array
  • Swift – Append String to Array
  • Swift – Concatenate two Arrays
  • Swift – Delete First N Elements of Array
  • Swift – Delete Last N Elements of Array
  • Swift – Delete First Element of Array
  • Swift – Delete Last Element of Array
  • Swift – Insert an Element in Array at Specific Index
  • Swift – Insert Elements of Another Array at Specific Index in this Array
  • Swift – Remove an element from Array
  • Swift – Remove Elements from Array based on a Condition
  • Swift – Remove all Elements from Array
  • Swift – Replace an Element in Array
  • Swift – Reverse an Array
  • Sort Arrays
  • Swift – Sort Integer Array in Ascending Order
  • Swift – Sort Integer Array in Descending Order
  • Swift – Sort String Array Lexicographically
  • Filter Arrays
  • Swift – Filter Array based on Condition
  • Swift – Filter only Even Numbers from Integer Array
  • Swift – Filter only Odd Numbers from Integer Array
  • Swift – Filter Strings in Array based on Length
  • Sets Basics
  • Swift – Create an Empty Set
  • Swift – Create Set from Array
  • Swift – Print Elements of Set
  • Swift – Set Size
  • Swift – Iterate over Set
  • Swift – Get Random Element from Set
  • Sets Checks
  • Swift – Check if Set is Empty
  • Swift – Check if Element is present in Set
  • Comparing Sets
  • Swift – Check if two Sets are Equal
  • Swift – Check if two Sets are Not Equal
  • Swift – Check if this Set is Subset of Another Set
  • Swift – Check if this Set is Superset of Another Set
  • Swift – Check if two Sets are Disjoint
  • Find in Sets
  • Swift – Find Minimum Element in a Set
  • Swift – Find Maximum Element in a Set
  • Sets Update / Transform
  • Swift – Insert Element to Set
  • Swift – Remove Element from Set
  • Swift – Shuffle Elements of a Set
  • Swift – Sort Elements of a Set
  • Set Operations
  • Swift – Union of Sets
  • Swift – Intersection of Sets
  • Swift – Initialize a Tuple
  • Swift – Get Element of a Tuple at Specific Index
  • Swift – Update Element of a Tuple at Specific Index
  • Swift – Initialize a Tuple with Labels for Values in it
  • Swift – Access Values of a Tuple using Labels
  • Swift – Create Dictionary
  • Swift – Create Dictionary using Arrays.
  • Swift – Iterate over Dictionary
  • Swift – Get Dictionary size.
  • Swift – Check if Dictionary is Empty
  • Swift – Add / Append Element to Dictionary
  • Swift – Get Value using Key from Dictionary.
  • Swift – Check if Specific Key is present in Dictionary
  • Swift – Merge two Dictionaries
  • Swift – Convert a Dictionary into Arrays of Keys and Values
  • Swift – Iterate over Keys in Dictionary
  • Swift – Print Dictionary Keys
  • Swift Struct
  • File Operations
  • Swift – Read Text File
  • Swift – Create Text File
  • Directory Operations
  • Swift – Create Directory at Specific Path
  • Swift – Get Items in a Directory
  • Swift – Get Home Directory for Current User
  • Keywords in Declarations
  • Keywords in Statements
  • ❯ Swift Tutorial
  • ❯ Swift Conditional Statements

Swift Conditional Statements

Swift Conditional Statements are those which execute a block of code based on the result of a condition or boolean expression.

Swift supports following conditional statements.

  • Swift If Statement
  • Swift If-Else Statement
  • Swift Switch Statement

We can use Logical Operators to form compound conditions. The following tutorials cover some of the scenarios where logical operators are used in conditions of Swift Conditional statements.

  • Swift If with AND Operator
  • Swift If with OR Operator
  • Swift If with NOT Operator

The following cover some of the conditional statements in Swift Programming.

If Statement

In the following example, we take an integer a = 10  and check if variable a is less than 20 . Since the condition evaluates to true , the statements inside the if block execute.

If-Else Statement

In the following example, we take an integer a = 30  and check if variable a is less than 20. As the expression evaluates to false, the statements inside the else block execute.

Switch Statement

In the following example, we have a simple expression with two variables. We have case blocks with values 4, 5, 6 and default. When the expression’s value matches any of the values, corresponding block is executed.

In this Swift Tutorial , we have learned about conditional statements in Swift Programming.

Popular Courses by TutorialKart

App developement, web development, online tools.

Swift Conditionals: `if`

New Courses Coming Soon

Join the waiting lists

This tutorial belongs to the Swift series

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 ran 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:

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

Here is how can I help you:

  • COURSES where I teach everything I know
  • CODING BOOTCAMP cohort course - next edition in 2025
  • THE VALLEY OF CODE your web development manual
  • BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
  • Interesting links collection
  • Follow me on X

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 Operator precedence and associativity

Swift if, if...else Statement

Swift Bitwise and Bit Shift Operators

Swift Ternary Conditional Operator

A ternary operator can be used to replace the if...else statement in certain scenarios.

Before you learn about the ternary operator, make sure to know about Swift if...else statement .

  • Ternary Operator in Swift

A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is

Here, the ternary operator evaluates condition and

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

  • Example: Swift Ternary Operator

In the above example, we have used a ternary operator to check pass or fail.

let result = (marks >= 40) ? "pass" : "fail"

Here, if marks is greater or equal to 40 , pass is assigned to result . Otherwise, fail is assigned to result .

  • Ternary operator instead of if...else

The ternary operator can be used to replace certain types of if...else statements. For example,

You can replace this code

Here, both programs give the same output. However, the use of the ternary operator makes our code more readable and clean.

  • Nested Ternary Operators

We can use one ternary operator inside another ternary operator. This is called a nested ternary operator in Swift. For example,

The number is Positive.

In the above example, we the nested ternary operator ((num > 0) ? "Positive" : "Negative" is executed if the condition num == 0 is false .

Note: It is recommended not to use nested ternary operators as they make our code more complex.

Table of Contents

  • Introduction

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Swift Tutorial

  • App development >
  • Design >
  • References >
  • About us >
  • Contact >

Conditional Assignment Operator

Jan Mísař

  • Development
  • Mobile apps
  • Uncategorized

conditional assignment swift

Very often developers need to build dictionaries from optional values. Sure, it’s pretty easy to do it in Swift , right? It’s just [ String: Any? ]  , so why write a blog post about it? We will use it as one of our use cases for our handy conditional assignment operator.

So let’s look at an example from a real life project - Zonky. The app presents a screen where you can select multiple loan parameters to filter the list of loans. 

conditional assignment swift

All of these parameters are optional of course. In order to apply the selected filters, we need to send the parameters to a server as a dictionary. A filtering function with the dictionary can look like this:

It seems to be OK, but we don’t want optionals in our dictionary because Alamofire takes [ String: Any ]   as a type of parameter dictionary. How do we fix that? The most straightforward solution is pretty obvious:

Fine, it works, but imagine a larger set of parameters. That’s a lot of ugly and boring code! ? That’s what leads us to the idea behind our conditional assignment operator. We want to assign a value to the dictionary only if it’s not nil.

Voilà. Shorter, nicer, more readable ? But it’s not the standard operator included in Swift, so let’s look at how it works under the hood. The basic idea is simple- we just moved the unwrapping and assignment code used in the second example to the custom operator definition.

And that’s it! We have a small piece of code which makes our codebase much nicer. You can use this operator not only for building dictionaries (there are other and maybe even smarter ways to achieve this) but whenever you need to assign value only if it’s not nil, and trust me, it’s a very common case, and you will like it ?

If you like this simple trick, see our ACKategories - lightweight open source library full of similar useful tools and extensions, or just wait for our next blog posts, and we will show you more recipes from our kitchen ?‍?

  • Conditional assignment operator

You may also like

conditional assignment swift

Introduction to Gemini SDK

Jan Steuer

Orval – generating TypeScript from OpenAPI

Martin Macura

Options for manipulating cache in Tanstack Query

Are you interested in working together let’s discuss it in person, get in touch >.

Syntactic sugar for assigning Optional values and conditional assignment

Hi Team! I hope you are doing well. I'm sorry for such a minor ideas but for my project they will make code more compact.

  • Assigning optional only if it has a value. E.g.: var a: Int? var b = 0 instead of: if (a != nil ) { b = a } use short: b =? a I can do it by implementing a custom operator but I think it's good to have it in the standard library: infix operator =? : AssignmentPrecedence extension Int { static func =?(left: inout Int, right: Int?) { if right != nil { left = right! }} }
  • The second idea for the conditional assignment I don't know how to implement by myself. E.g. let c = 0 var d = 0 we have a ternary operator for the case when we want to assign an alternative value in case some condition is false: d = c > 0 ? c : 1 but if we don't want to use any alternative then we need to write code like this: if (c > 0) { d = c } My suggestion is to simplify the syntax somehow. E.g.: d = c > 0 ? c or d = c > 0 ? c : _ I understand that the proposals are looking as they're out of thin air, but when you are reading dozens of parameters from the external source it's good to make it as short as possible.

Thank you in advance!

Best regards, Vsevolod Migdisov

You can also do b = a ?? b

(it’s not quite the same as in b will be reassigned if a is nil , but the end result is the same i.e b will either contain the value stored in a or 0 )

I think this is just d = max(c, 1) .

Similarly, you can write this as d = max(c, d) , although I prefer the original.

Do you have any other examples where the syntactic sugar for ternary operations might offer an improvement? Syntactic sugar additions have a very high bar for entry into the language.

I do the same in my code for both proposals - if condition is false then I assign the variable itself. But I think it looks not quite elegant: b = a ?? b d = c > 0 ? c : d

Both proposals are not just for Int. It can be applied to String as well or any other types: if (str != "") { str = "some string") The idea is that if the condition is false then no assignment should be done. The same as in the 1st proposal - if the value is nil then don't do the assignment at all.

Okay. It looks like the =? change has been pitched before and rejected, so I’m not sure if it’s worth pursuing.

The other change you mentioned doesn’t look like it’s been pitched before, so perhaps you can just focus on that.

I personally don’t see a need to optimize the syntax for if (c > 0) { d = c } as I think it is perfectly fine to write and is readable.

Thanks a lot, Suyash!

Swift requires braces for all if statements, so parentheses aren't needed like they are in other languages.

:world_map:

I've found both solutions for myself but I still think it's good to have it in the standard library: infix operator ?= : AssignmentPrecedence func ?=< T >(lhs: inout T, rhs: T?) { if rhs != nil { lhs = rhs! } } func ?=< T >(lhs: inout T, rhs: (Bool, T)) { if rhs.0 { lhs = rhs.1 } }

No please don't use map for side-effects! There should be a forEach but for optionals, but until we have that please let's all keep map functional!

Instantly share code, notes, and snippets.

@PetrusM

PetrusM / ConditionalAssignmentOperators.swift

  • Download ZIP
  • Star ( 0 ) 0 You must be signed in to star a gist
  • Fork ( 0 ) 0 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save PetrusM/8a8eadbd790e48a3f1b508895ea37262 to your computer and use it in GitHub Desktop.
// MARK: - Not nulling assignment
precedencegroup NotNullingAssignment
{
associativity: right
}
// This operators does only perform assignment if the value (right side) is not null.
infix operator =?: NotNullingAssignment
public func =?<T>(variable: inout T, value: T?)
{
if let value = value
{
variable = value
}
}
// This case is also necessary, because the previous one does not work is `variable`
/// is also optional, because in this case `T` would represent an optional.
public func =?<T>(variable: inout T?, value: T?)
{
if let value = value
{
variable = value
}
}
// MARK: - Not crushing assignment
precedencegroup NotCrushingAssignment
{
associativity: right
}
// This operators does only perform assignment if the variable (left side) is null.
infix operator ?=: NotCrushingAssignment
public func ?=<T>(variable: inout T?, value: T)
{
if variable == nil
{
variable = value
}
}
/// This case is also necessary, because the previous one does not work is `variable`
/// is also optional, because in this case `T` would represent an optional.
public func ?=<T>(variable: inout T?, value: T?)
{
if variable == nil
{
variable = value
}
}

@PetrusM

PetrusM commented Mar 3, 2023 • edited Loading

?= : Assignment is performed only if the variable (left side) is null - it does not crush any value. =? : Assignment is performed only if the new value (right side) is not null.

Sorry, something went wrong.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Single line if statement in Swift

How would one convert the following to Swift from Objective-C?

Swift does not use parentheses around the conditional, however the following code gives an error.

  • objective-c

Azhar's user avatar

  • 7 Unlike Objective C, braces are mandatory while using if statements in Swift. The reason behind this is to make the code safer. –  ZeMoon Commented Jun 11, 2014 at 9:01
  • you have to add the braces {} for all branches, but the parenthesis are optional () , you can keep them if you'd like to. –  holex Commented Jun 11, 2014 at 12:59

8 Answers 8

Well as the other guys also explained that braces are a must in swift. But for simplicity one can always do something like:

4aRk Kn1gh7's user avatar

In Swift the braces aren't optional like they were in Objective-C (C). The parens on the other hand are optional. Examples:

Valid Swift:

Invalid Swift:

This design decision eliminates an entire class of bugs that can come from improperly using an if statement without braces like the following case, where it might not always be clear that something 's value will be changed conditionally, but somethingElse 's value will change every time.

Mick MacCallum's user avatar

  • 7 One example of a widely publicized bug which is related to this, is Apple's SSL/TLS bug , while Swift was in development. I sometimes wonder if this design decision was made because of that, or if it's just coincidental. It's an interesting detail of Swift, since it's very uncommon for "C like" languages to enforce a coding style. –  Jonas Commented Feb 5, 2015 at 12:29
  • Apple's SSL/TLS bug - doesn't indicate that single line If's are the problem. It clearly shows that CMD+V should not use "Key-delay" and "key-repeat" setting of keyboard and should paste only once. Try copying one line of text and press CMD+V a little longer than usual. That's unless, developer purposely put two consecutive "goto fail;" assuming to work in a single if block, to make sure that if in case the control pointer does not obey the first time, repeating a second time would help. "You still here ???? I have already told you to goto fail.... GOTO FAIL this instant !!!" –  Nikhil Mathew Commented Aug 2, 2016 at 19:10
  • You can't put parenthesis around if let statements. –  Iulian Onofrei Commented Nov 30, 2017 at 22:36

You can use new Nil-Coalescing Operator, since Swift 3 in case when you need just set default value in case of if fails:

In case if someOptional is false , this operator assign "" to someValue

One-line if , one-line while and one-line for are considered a bad style by many developers because they are less readable and allegedly a source of many errors.

Swift solved the conundrum by forbidding one-line flow control statements; the braces are non-optional...

Of course, you can still do

There are also implementation reasons. Having the parentheses around the condition as optional makes the parsing much harder. Enforcing braces simplifies parsing again.

Frank Schmitt's user avatar

  • "Alleged" is about right. With conventions such as consistent use of Allman braces and indentation, it was already very preventable. –  Peter DeWeese Commented Jul 26, 2014 at 1:45

Here is a simple solution I used in my projects.

Sathya Baman's user avatar

One line solution for Swift 3+

Mike Karpenko's user avatar

Swift 5 Easy One line Solution

Shakeel Ahmed's user avatar

  • 1 I think swift conventions says to not use parenthesis on if statements –  Javier Heisecke Commented Oct 7, 2021 at 15:58

Swift 5 Easy Solution

enter image description here

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 ios objective-c swift swift3 swift4 or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Topos notions coming from topology and uniqueness of generalizations
  • What is the first work of fiction to feature a vampire-human hybrid or dhampir vampire hunter as a protagonist?
  • Show that an operator is not compact.
  • No displayport over USBC with lenovo ideapad gaming 3 (15IHU6)
  • Enumitem + color labels + multiline = bug?
  • What was the first "Star Trek" style teleporter in SF?
  • What other crewed spacecraft returned uncrewed before Starliner Boe-CFT?
  • Does a party have to wait 1d4 hours to start a Short Rest if no healing is available and an ally is only stabilized?
  • How can I play MechWarrior 2?
  • Hashable and ordered enums to describe states of a process
  • PCA to help select variables?
  • Visual assessment of scatterplots acceptable?
  • how do I fix apt-file? - not working and added extra repos
  • Is it a good idea to perform I2C Communication in the ISR?
  • Approximations for a Fibonacci-Like Sequence
  • "Mixture, Pitch then Power" - why?
  • In which town of Europe (Germany ?) were this 2 photos taken during WWII?
  • Nausea during high altitude cycling climbs
  • How to connect 20 plus external hard drives to a computer?
  • How does the phrase "a longe" meaning "from far away" make sense syntactically? Shouldn't it be "a longo"?
  • What's the purpose of scanning the area before opening the portal?
  • Websites assume the wrong country after using a VPN
  • Can reinforcement learning rewards be a combination of current and new state?
  • In a tabular with p-column, line spacing after multi-line cell too short with the array package

conditional assignment swift

COMMENTS

  1. Assign conditional expression in Swift?

    Swift 2.0 conditional assignment and syntax. 4. Ternary Conditional Operator for else if. 8. Python style conditional expression in Swift 3. 1. Setting variable equal to if statement condition. 0. if conditions in the swift. Hot Network Questions

  2. The Ultimate Guide to Swift Conditionals

    Swift is a beautiful language that was carefully designed and has greatly evolved since it was announced back in 2014. ... The ternary operator lets you inline a conditional assignment where you ...

  3. Basic Operators

    Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c). The values that operators affect are operands. In the expression 1 + 2, the + symbol is an infix operator and its two operands are the values 1 and 2. Assignment Operator. The assignment operator (a = b) initializes or updates the value of a with the ...

  4. if and switch expressions

    Available from Swift 5.9. SE-0380 adds the ability for us to use if and switch as expressions in several situations. This produces syntax that will be a little surprising at first, but overall it does help reduce a little extra syntax in the language. As a simple example, we could set a variable to either "Pass" or "Fail" depending on a ...

  5. Learn Swift: Conditionals & Logic Cheatsheet

    The switch statement is a type of conditional used to check the value of an expression against multiple cases. A case executes when it matches the value of the expression. When there are no matches between the case statements and the expression, the default statement executes. var secondaryColor = "green". switch secondaryColor {.

  6. Conditional statements

    Conditional statements - a free Hacking with Swift tutorial

  7. Use if/else and switch statements as expressions in Swift 5.9

    Now, with Swift 5.9, you can leverage if/else expressions. This allows you to use a more familiar and readable chain of if statements. Below is the transformed code: let result = if condition1 {. value1. } else if condition2 {. value2. } else if condition3 {. value3.

  8. Swift if else, switch case Conditional Statements

    Swift if else, switch case Conditional Statements. To put it simply, a group of code, when executed on a particular/certain conditions, are known as conditional statements. You can quickly identify them by figuring out some noticeable terms like if, if ...else, switch case. Generally, developers use it when needed to execute the code on a ...

  9. Conditional compilation within Swift expressions

    Inline checks within expressions. When using Swift 5.5, we now have the option to inline #if directives right within our expressions. So, going back to our ItemList, we can now conditionally apply each of our listStyle modifiers completely inline — without first having to break our expression up into multiple parts: struct ItemList: View {.

  10. Swift Conditional Statements

    If-Else Statement. In the following example, we take an integer a = 30 and check if variable a is less than 20. As the expression evaluates to false, the statements inside the else block execute. main.swift. var a:Int = 30. /* condition to check if a is less than 20 */. if a < 20 {. /* if block statements */. print("a is less than 20.")

  11. Swift Conditionals: `if`

    Join the waiting lists This tutorial belongs to the Swift series. 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 ran if the condition is true:. let condition = true if condition == true {// code executed if the condition is true}. An else block is executed if the ...

  12. Conditional assignment operator

    Finally, no further need for (ugly) workarounds: async-await; Swift 5.5! Using Custom Strongly Typed Values For Better Coding in Swift How a well-crafted function for Decodable data request should be

  13. Swift if, if...else Statement (With Examples)

    Swift if, if...else Statement. In computer programming, we use the if statement to run a block code only when a certain condition is met. For example, assigning grades (A, B, C) based on marks obtained by a student. if the percentage is above 90, assign grade A. if the percentage is above 75, assign grade B.

  14. 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. condition ? expression1 : expression2

  15. Swift Insight: Conditional assignment operator

    Very often developers need to build dictionaries from optional values. Sure, it's pretty easy to do it in Swift, right? It's just [String: Any?] , so why write a blog post about it? We will use it as one of our use cases for our handy conditional assignment operator. So let's look at an example from a real life project - Zonky.

  16. Syntactic sugar for assigning Optional values and conditional assignment

    The second idea for the conditional assignment I don't know how to implement by myself. E.g. let c = 0 var d = 0 ... Swift requires braces for all if statements, so parentheses aren't needed like they are in other languages. if c > 0 { d = c } As for the first example, use map!

  17. Swift : Conditional assignment operators · GitHub

    Swift : Conditional assignment operators. GitHub Gist: instantly share code, notes, and snippets.

  18. Is there a way to do conditional assignment to constants in Swift?

    4. You could also do this. if #available(iOS 9, *) {. return "iOS 9". } else {. return "not iOS 9". By doing this you can't assign a value to the variable someConstant even if it is a var and not a let because it is a calculated property. Another way of doing this would be to use free functions. if #available(iOS 9, *) {.

  19. ios

    Apple's SSL/TLS bug - doesn't indicate that single line If's are the problem. It clearly shows that CMD+V should not use "Key-delay" and "key-repeat" setting of keyboard and should paste only once. Try copying one line of text and press CMD+V a little longer than usual.