Swift Syntax Cheat Sheet



Swift Syntax Cheat Sheet

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. Swift 5.1 Cheat Sheet and Quick Reference. // Initializer syntax let anotherEmptyString // Mutating a string displays the Using string String message. 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. Swift 5.1 Cheat Sheet and Quick Reference. Declaring Constants and Variables // Declaring a constant using the let keyword let double: Double =. // Initializer syntax let anotherEmptyString // Mutating a string displays the Using string String message literal ) var mutableString 'Swift.

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

Swift Syntax Cheat Sheet

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.

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 {}

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.

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

Swift 5 pdf

Why learn by heart if you can cheat? Grab my open source cheatsheet for Swift 5, including common syntax for functions, variables, collections, Object-Oriented Programming, closures, generics, error handling and more!

In This Cheatsheet

Compared to the previous versions of the cheatsheet, a lot has changed. It’s expanded, made clearer, upgraded and updated. I’ve added explanations alongside the code examples to help beginner iOS developers get to grips with Swift from a birds-eye view.

This cheatsheet includes:

  • Variables, including primitives and common variable types
  • Functions, including function declaration and usage
  • Operators, from logical operators to ranges to math – it’s in here
  • Classes, including class declaration, protocols, outlets, properties, initializers, extensions, lazy properties and class methods
  • Instances, including initialization and using properties
  • Control Flow, including if-elseif-else statements and switch
  • Loops, including for, while and Swift range syntax
  • Conditionals, including expressions, boolean logic and operators
  • Strings, including working with strings, converting from String to Int, and string interpolation
  • Optionals, including optional binding, optional chaining and force unwrapping
  • Dictionaries, including initialization and accessing key-value pairs
  • Arrays, including accessing values, adding values and looping over values
  • Sets, including what makes them special compared to dictionaries and arrays
  • Closures, including complete closure syntax, capturing and escaping
  • Guard & Defer, including early return with guard and deferred execution with defer
  • Generics, including generic types and function generics
  • Tuples, because while I’m at it I might as well add tuple syntax too…
  • Enumerations, including raw values, associated values and using enums with switch
  • Error Handling, including throwing errors and catching them with do-try-catch
Syntax

The Swift Cheatsheet Is Open Source

Good things happen when you work together! My Swift 5 cheatsheet is open source. This means you can do with it whatever you want, as long as you keep the open source license intact.

The most successful people I know share their work. As you’re learning how to code iOS apps, making this your practice is essential.

Can you help? Contribute your Swift code examples, tidbits and cheats by creating a Pull Request (PR) on GitHub. If you have an idea or found a bug, please share it by creating an Issue ticket.

And of course – help your fellow coder to cheat by passing along this Swift cheatsheet!

Try Out Your Code In The Swift Sandbox

Don’t got Xcode or Playgrounds handy? Try your favorite Swift tricks with the handy Swift sandbox below. It couldn’t be simpler: just type in your code and click “Run”.

Swift 5 Cheat Sheet

let greeting = 'Hello world!'
for _ in 1...5 {
print(greeting)
}
Swift

Further Reading

Swift Syntax Cheat Sheet Pdf

Save the whales, the trees and the arctic, and don’t print out this cheatsheet! Simply save the PDF and keep it open while you’re coding.

Swift 5 Syntax Cheat Sheet

Want to learn more? Check out these resources: