Swift Syntax Cheat Sheet



If you want the old style of modal presentation where a modal view is presented full screen, you can use.fullScreenCover instead of.sheet. Since the full-screen cover style doesn't allow a user to use gesture to dismiss the modal, you have to add a way to dismiss the presented view manually. Cheat sheets are very useful when we need to get quick help while coding and every programmer likes to keep some helpful cheat sheets by his/her side. Swift Cheat Sheet; Swift fossBytes Academy. Looking for more Cheat Sheets for Swift like this. Anyone knows a more complete Cheat Sheet/scheme for Swift? The developer may not know the sheet is out of date; thus relying on a sheet like this perpetuates incorrect syntax. 1 point 1 year ago. This guy/gal develops. Per the last couple of. To change the value of a key-value pair, use the.updateValue method or subscript syntax by appending brackets with an existing key inside them to a dictionary’s name and then adding an assignment operator (=) followed by the modified value.

The function is a self-containing block of code for performing the specific task. The function is a thing, that we use every day. It’s like a building block for our code.

The general form of the Swift function is:

Let’s see it closer using sample:

NotationMeaning
funcDenotes that this is a function
doSomethingCoolName of the function
(foo: FooType, withBar bar: BarType, andBuz buz: BuzType)Parameters of the function
foo, bar, bazParameters variable names
withBar, andBuzParameters names
FooType, BarType, BazTypeParameters types
ResultTypeThe type of the returned result. Can be empty (Void)
{}Contains function body

Simplest function

The function can be simple. Let’s check the simplest one.It starts with func keyword and named printMessage, does not have arguments nor return value. It just performs code contained inside curly braces {...}

Syntax

Parameters syntax

The function can accept parameters. For example, the following function accepts singleString parameter with the name name.

Swift

The function can accept multiple parameters.

If you want to omit parameter names replace them with _.That’s how previous function call will look like with second parameter name omitted:

Named parameters

If you want to make all parameters named, just type desired parameter name before the variable name. Just like in Objective-C.That’s how previous function will look like with named first parameter:

Parameters with default values

The function can have default parameter values. If you skip parameter in a function call, it will take a default value. Otherwise, it will take passed value.Parameter name from the next code sample has default value 'Neo'.

Swift Syntax Cheat Sheet 2020

Variadic parameters

Variadic parameters are handy when parameters count is unknown. Variadic parameter is transformed to Array<ParamType>.To mark parameter as variadic use name: <Type>... syntax. See the following sample:

In-out parameters

As mentioned above, variable parameters can only be changed by the function itself. If you need the function to change some parameters from outside the function scope, you should use inout keyword. Keep in mind that inout parameters cannot have default values.

Apps Built By Apple Swift

Generic parameters

We can rewrite swapAgents(_:_:) function in a more general way. Using the following notation we tell that function accepts two parameters of any type, but the type of the parameter a is always the same as the parameter b type

Return values syntax

Functions can return values. It is not required (all the functions above did not return any values). Basically, functions are small programs, which can return results of their work.As you can see, isThereASpoon(_:) function returns the single value of Bool type. In Swift, return value type is separated from function name with -> symbol.

Multiple return values

Sometimes we need to receive multiple return values from a function. It is possible. Swift allows us to deal with it in an elegant way. The following code sample shows how to use and access multiple return values:

Swift Syntax Cheat Sheet

Optional tuple

If there is probability, that returning tuple will have no value, we should use an Optional tuple. The function above, rewritten with optional tuple, will look like this:

You can pass any function as an argument or use it as a return value of any other function. In Swift, functions are first-class citizens. Function has a type. Function type general form is (argument types) -> return type. In the example below, both functions, plus(_: _:) and multiply(_: _:) has the same type: (Int, Int) -> Int. calculate(_: _: _:) function uses proper function depending on the operation passed as argument.

Function as return value

Function can also be used as return type of other function. mathFunction(_:) returns (Int, Int) -> Int function, which is used by calculate(_: _: _:) function from the previous example;

The type of the function can be named using typealias keyword. Let’s rewrite our math functions using typealas.

Nested functions

Nested functions are functions, used inside the other functions.

Conclusion

Functions in Swift are powerful and flexible. Different syntactical possibilities can be used to improve code informativity and reduce clatter.

Further reading

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios.

For better understanding, I strongly recommend you to read Swift functions cheatsheet

Closure syntax

Since any function is the special case of closure, they are very similar. Basic difference is the way of writing and the use purpose. Closures syntax is optimized to be convenient for inlining, passing as parameter and using as a return type of other functions.

The general form of the Swift closure is:

Everything looks familiar, except in keyword. in keyword denotes that parameters and return type section is over, and function body is started.

In terms of parameters and return types closures are identical to functions.

Let’s imagine, that we have a function, that takes two Int numbers and the function of type (Int, Int) -> Int, which applies operation on these two integers and returns result. We will rewrite this function few times during the article for the sake of undestanding and exploring the benefits of the closures.

Inlining

Lets delete the plus(_: _:) and the multiply(_: _;) functions. We will pass the function directly to the calculate(_: _: _:) as a parameter. We are using the canonical general form closure syntax.

Inferring type from context

We gonna use Type Inference. calculate(_: _: _:) expects, that operation parameter will have (Int, Int) -> Int type. So we can omit type declarations.

We can also delete the braces and the return statement.

Swift Syntax Cheat Sheet

Shorthand arguments

Despite the fact, that function call seems pretty even now, we can make it more compact and sofisticated using the shorthand argument syntax.

Trailing closures

If closure is the last argument in the function call, we can use the trailing closure syntax. Closure argument just goes out of braces. This way is handy when there are multiple lines between {}

Swift Syntax Cheat Sheet 2019

Capturing values

A closure can capture constants and variables from the surrounding context in which it is defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists. (Excerpt from Apple official documentations

Let’s clarify it. The simplest form of a closure, that can capture value is a nested function. Let’s take a closer look at the Apple’s sample from official documentation. makeIncrementer(_:) has return type () -> Int, therefore it returns function. The returned function takes runningTotal value, which is in the makeIncrementer(_:) scope, and adds amount to it. The reference to the value of runningTotal is captured from the functions context. Each the function is called, it will increment captured value. I strongly recommend to check official documentation to explore all other aspects of capturing.

Allways keep in mind, that closures are reference types.

Autoclosures

If you pass expression as an argument of a function, it will be automatically wrapped by autoclosure. You often call functions, that takes autoclosures, but it’s not common to implement that kind of functions. An autoclosure lets you to delay evaluation of the potentially slow code inside, until you call the closure.

You get the same behavior of delayed evaluation when you pass a closure as an argument to a function.

Rewriting the serveCustomer(_:) function by marking it’s parameter with @autoclosure attribute makes us able to call the function as if it took a string argument instead of a closure.

If you want an autoclosure that is allowed to escape, use @autoclosure @escaping form of the attribute.

Swift Syntax Cheat Sheet Download

Conclusions

Closures are not something just-invented. You can see, that they are the same as blocks. But syntax imrovements and Swift language features like type inferrence takes closures to the new level of convenience. Closure syntax allows us to write short, sofisticated code and use some of Functional Programming benefits.

Improper use of a closures can make your code hardly readable. So think about it as about sharp knife in your hand. It can do good job, but can easuily cut off your finger in case of unsafe usage.

Further reading