{"id":49454769,"url":"https://github.com/reinder42/SwiftCheatsheet","last_synced_at":"2026-06-18T23:00:45.405Z","repository":{"id":43174613,"uuid":"111714450","full_name":"reinder42/SwiftCheatsheet","owner":"reinder42","description":"A cheatsheet for Swift 5. Including examples of common Swift code and short explanations of what it does and how it works. Perfect for beginner iOS developers!","archived":false,"fork":false,"pushed_at":"2023-01-26T08:40:20.000Z","size":987,"stargazers_count":577,"open_issues_count":0,"forks_count":113,"subscribers_count":35,"default_branch":"master","last_synced_at":"2023-11-07T14:16:40.570Z","etag":null,"topics":["cheatsheet","ios","swift","swift5"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/reinder42.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-22T17:38:22.000Z","updated_at":"2023-11-02T00:38:21.000Z","dependencies_parsed_at":"2023-02-14T15:31:22.508Z","dependency_job_id":null,"html_url":"https://github.com/reinder42/SwiftCheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":null,"template_full_name":null,"purl":"pkg:github/reinder42/SwiftCheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reinder42%2FSwiftCheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reinder42%2FSwiftCheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reinder42%2FSwiftCheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reinder42%2FSwiftCheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/reinder42","download_url":"https://codeload.github.com/reinder42/SwiftCheatsheet/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reinder42%2FSwiftCheatsheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34510287,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-18T02:00:06.871Z","response_time":128,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","ios","swift","swift5"],"created_at":"2026-04-30T05:00:30.603Z","updated_at":"2026-06-18T23:00:45.397Z","avatar_url":"https://github.com/reinder42.png","language":null,"funding_links":[],"categories":["📱 - Mobile apps\u003ca name=\"4\"\u003e\u003c/a\u003e"],"sub_categories":["Swift\u003ca name=\"4a\"\u003e\u003c/a\u003e"],"readme":"# Swift 5 Cheatsheet\n\nA cheatsheet for Swift 5. Including examples of common Swift code and short explanations of what it does and how it works. Perfect for beginner iOS developers!\n\n## How to Use\n\nThe cheatsheet is in Markdown format. Simply read the cheatsheet online, or download the repository and open it. Use your favorite Markdown editor to export to PDF or HTML.\n\nAlthough we'd love for you to print it out and hang it on your desk, please think about the environment.\n\n## Contributing\n\nWant to help create the most comprehensive (and concise!) Swift cheatsheet ever? There's a few ways you can help:\n\n- Suggest code examples, topics and cheat sheet items by [creating an Issue](https://github.com/reinder42/SwiftCheatsheet/issues)\n- Add your own code examples by creating a Pull Request\n- Share this cheatsheet with iOS developers you know to spread the word\n\nFor more information, please check the [contribution guidelines](https://github.com/reinder42/SwiftCheatsheet/blob/master/CONTRIBUTING.md).\n\nDistributed under the MIT license. See [LICENSE](LICENSE) for more information.\n\n## Table Of Contents\n\n- [Variables](#variables)\n- [Functions](#functions)\n- [Operators](#operators)\n- [Classes, Objects, Properties](#oop)\n- [Structs](#structs)\n- [Protocols](#protocols)\n- [Control Flow](#control-flow)\n    + [Conditionals](#conditionals)\n    + [Loops](#loops)\n    + [Switch](#switch)\n- [Strings](#strings)\n- [Optionals](#optionals)\n- [Collections](#collections)\n    + [Arrays](#arrays)\n    + [Dictionaries](#dictionaries)\n    + [Sets](#sets)\n- [Closures](#closures)\n- [Guard and Defer](#guard-defer)\n    + [Guard](#guard)\n    + [Defer](#defer)\n- [Generics](#generics)\n- [Tuples](#tuples)\n- [Enumerations](#enums)\n- [Error Handling](#error-handling)\n- [Commenting](#commenting)\n- [Resources](#resources)\n\n## \u003ca name=\"variables\"\u003e\u003c/a\u003eVariables\n\nUse `var` for variables that can change (\"mutable\") and `let` for constants that can't change (\"non-mutable\").\n\n_Integers_ are \"whole\" numbers, i.e. numbers without a fractional component.\n\n```swift\nvar meaningOfLife: Int = 42\n```\n\n_Floats_ are decimal-point numbers, i.e. numbers with a fractional component.\n\n```swift\nvar phi: Float = 1.618\n```\n\n_Doubles_ are floating point numbers with double precision, i.e. numbers with a fractional component. Doubles are preferred over floats.\n\n```swift\nlet pi: Double = 3.14159265359\n```\n\nA _String_ is a sequence of characters, like text.\n\n```swift\nvar message: String = \"Hello World!\"\n```\n\nA _boolean_ can be either `true` or `false`. You use booleans for logical operations.\n\n```swift\nvar isLoggedIn: Bool = false\n```\n\nYou can assign the result of an expression to a variable, like this:\n\n```swift\nvar result: Int = 1 + 2\n```\n\nAn _expression_ is programmer lingo for putting stuff like variables, operators, constants, functions, etc. together. Like `a + b` in this example:\n\n```swift\nlet a = 3\nlet b = 4\nlet c = a + b\n```\n\nSwift can determine the _type_ (`Int`, `Double`, `String`, etc.) of a variable on its own. This is called _type inference_. In this example, the type of `name` is inferred to be `String`.\n\n```swift\nvar name = \"Arthur Dent\"\n```\n\nVariables can be _optional_, which means it either contains a value or it's `nil`. Optionals make coding Swift safer and more productive. Here's an optional string:\n\n```swift\nvar optionalMessage: String?\n```\n\n## \u003ca name=\"functions\"\u003e\u003c/a\u003e Functions\n\n_Functions_ are containers of Swift code. They have input and output. You often use functions to create abstractions in your code, and to make your code reusable.\n\nHere's an example of a function:\n\n```swift\nfunc greetUser(name: String, bySaying greeting:String = \"Hello\") -\u003e String\n{\n    return \"\\(greeting), \\(name)\"\n}\n```\n\nThis function has two _parameters_ called `name` and `greeting`, both of type `String`. The second parameter `greeting` has an _argument label_ `bySaying`. The return type of the function is `String`, and its code is written between those squiggly brackets.\n\nYou call the function like the following. The function is called, with two arguments, and the return value of the function is assigned to `message`.\n\n```swift\nlet message = greetUser(name: \"Zaphod\", bySaying: \"Good Morning\") \n```\n\nCourses, books, documentation, etc. uses a special notation for function signatures. It'll use the function name and argument labels, like `greetUser(name:bySaying:)`, to describe the function.\n\n## \u003ca name=\"operators\"\u003e\u003c/a\u003e Operators\n\nThe _assignment operator_ `=` assigns what's right of the operator to what's left of the operator. Don't confuse it with `==`!\n\n```swift\nlet age = 42\n```\n\nSwift has a few basic math operators:\n\n- `a + b` for _addition_ (works for strings too)\n- `a - b` for _subtraction_\n- `a * b` for _multiplication_\n- `a / b` for _division_\n- `a % b` for _remainder_ (or use `isMultiple(of:)`)\n- `-a` for _minus_ (invert sign)\n\nUnlike other programming languages, Swift does not have `--` and `++` operators. Instead it has:\n\n- `a += b` for _addition_, such as `n += 1` for `n++` or `n = n + 1`\n- `a -= b` for _subtraction_, such as `n -= 1` for `n--` or `n = n - 1`\n\nYou can also use `+=` for arrays:\n\n```swift\nvar rappers = [\"Eminem\", \"Jay-Z\", \"Snoop Dogg\"]\nrappers += [\"Tupac\"]\n```\n\nSwift has 6 comparison operators:\n\n- `a == b` for _equality_, i.e. \"a is equal to b\"\n- `a != b` for _inequality_, i.e. \"a is not equal to b\"\n- `a \u003e b` for _greater than_, i.e. \"a is greater than b\"\n- `a \u003c b` for _less than_, i.e. \"a is less than b\"\n- `a \u003e= b` for _greater than or equal_\n- `a \u003c= b` for _less than or equal_\n\nSwift also has the identity operators `===` and `!==`. You can use them to test if two variables reference the exact _same object_. Contrast this with `==` and `!=`, which merely test if two objects are equal to each other.\n\nYou can also compare strings, which is helpful for sorting. Like this:\n\n```swift\n\"abc\" \u003e \"xyz\"         // false\n\"Starbucks\" \u003e \"Costa\" // true\n\"Alice\" \u003c \"Bob\"       // true\n```\n\nSwift has 3 logical operators:\n\n- `a \u0026\u0026 b` for _Logical AND_, returns `true` if `a` and `b` are `true`, or `false` otherwise\n- `a || b` for _Logical OR_, returns `true` if either `a` or `b` is `true`, or both are `true`, or `false` otherwise\n- `!a` for _Logical NOT_, returns `true` if `a` is `false`, and `false` if `a` is `true` (i.e., the opposite of `a`)\n\nSwift has a few range operators. You can use them to define ranges of numbers and strings.\n\n- `a...b`, the _closed range operator_, defines a range from `a` to `b` including `b`\n- `a..\u003cb`, the _half-open range operator_, defines a range from `a` to `b` _not_ including `b`\n\nYou can also use _one-sided ranges_. They're especially useful in arrays.\n\n- `a...` in `array[a...]` defines a range from `a` to the end of the array\n- `...a` in `array[...a]` defines a range from the beginning of the array to `a`\n- `..\u003ca` in `array[..\u003ca]` defines a range from the beginning of the array to `a`, not including `a` itself\n\n## \u003ca name=\"oop\"\u003e\u003c/a\u003e Classes, Objects, Properties\n\nClasses are basic building blocks for apps. They can contain functions, sometimes called _methods_, and variables, called _properties_.\n\n```swift\nclass Office: Building, Constructable\n{\n    var address: String = \"1 Infinite Loop\"\n    var phone: String?\n\n    @IBOutlet weak var submitButton:UIButton?\n\n    lazy var articles:String = {\n        return Database.getArticles()\n    }()\n\n    override init()\n    {\n        address = \"1 Probability Drive\"\n    }\n\n    func startWorking(_ time:String, withWorkers workers:Int)\n    {\n        print(\"Starting working at time \\(time) with workers \\(workers)\")\n    }\n}\n```\n\nThe class definition starts with `class`, then the class name `Office`, then the `Building` class it _inherits_ from, and then the `Constructable` _protocol_ it conforms to. Inheritance, protocols, all that stuff, is part of _Object-Oriented Programming_.\n\nProperties are variables that belong to a class instance. This class has 4 of them: `address`, `phone`, the outlet `submitButton` and the lazy computed property `articles`. Properties can have a number of attributes, like `weak` and `@IBOutlet`.\n\nThe function `init()` is _overridden_ from the superclass `Building`. The class `Office` is a _subclass_ of `Building`, so it inherits all functions and properties that `Building` has.\n\nYou can create an _instance_ of a class, and change its properties, like this:\n\n```swift\nlet buildingA = Office()\nbuildingA.address = \"Sector ZZ9 Plural Z Alpha\"\n```\n\nExtensions let you add new functions to existing types. This is useful in scenarios where you can't change the code of a class. Like this:\n\n```swift\nextension Building\n{\n    func evacuate() {\n        print(\"Please leave the building in an orderly fashion.\")\n    }\n}\n```\n\n## \u003ca name=\"structs\"\u003e\u003c/a\u003e Structs\n\nStructs or _structures_ in Swift allow you to encapsulate related properties and functionality in your code, that you can reuse. Structs are value types.\n\nWe declare them like this:\n\n```swift\nstruct Jedi {\n    var name: String\n    var midichlorians: Int\n}\n```\n\nYou can create an instance of the `Jedi` struct like this:\n\n```swift\nvar obi_wan = Jedi(name: \"Obi-Wan Kenobi\", midichlorians: 13400)\n```\n\nHere's how you can read a property from `obi_wan`:\n\n```swift\nprint(obi_wan.midichlorians)\n// Output: 13400\n```\n\nWe can also include functions inside our structs, like this:\n\n```swift\nstruct Jedi {\n    var name: String\n    var midichlorians: Int\n\n    func mindTrick() {\n        print(\"These aren't the Droids you're looking for...\")\n    }\n}\n\n// Instance of a struct\nvar obi_wan = Jedi(name: \"Obi-Wan Kenobi\", midichlorians: 13400)\n\n// Reading a property\nprint(obi_wan.midichlorians) \n\n// Calling mindTrick() function\nobi_wan.mindTrick()\n```\n    \n## \u003ca name=\"protocols\"\u003e\u003c/a\u003e Protocols\n\nProtocols define a \"contract\"; a set of functions and properties that a type, like a class, must implement if it wants to _conform_ to the protocol.\n\nProtocols are declared like this:\n\n```swift\nprotocol Healer {\n    func heal()\n}\n```\n\nIn this example Imperial troops are fine on their own, but can conform to the `Healer` protocol and support their fellow troopers in combat:\n\n```swift\nprotocol Healer {\n    func heal()\n}\n\nstruct TiePilot {\n    var starfigherModel: String = \"TIE/IN Interceptor\"\n    var rank: String = \"Lieutenant\"\n}\n\nstruct StormTrooper: Healer {\n    var name: String = \"TK-9091\"\n    var unit: String = \"501st Legion\"\n    \n    func heal() {\n        print(\"Deploying Advanced Medical Probe!\")\n    }\n}\n```\n\nYou can also use protocols as types. Like this:\n\n```swift\nstruct Squadron \n{\n    var leader: EliteStormTrooper\n    var troopers: [StormTrooper]\n    var healer: Healer\n\n    func init(...) { ... }\n}\n\nvar squad5 = Squadron(...)\nsquad5.healer = StormTrooper(...)\n```\n\nIn the above code, you can assign an object of type `StormTrooper` to the `healer` property of type `Healer`, because the `StormTrooper` type conforms to the `Healer` protocol. You can assign anything to it, as long as it conforms to the right protocol.\n\n## \u003ca name=\"control-flow\"\u003e\u003c/a\u003e Control Flow\n\n### \u003ca name=\"conditionals\"\u003e\u003c/a\u003e Conditionals\n\nThis is an `if`-statement, or _conditional_. You use them to make decisions based on logic.\n\n```swift\nif isActive\n{\n    print(\"This user is ACTIVE!\")\n} else {\n    print(\"Inactive user...\")\n}\n```\n\nYou can combine multiple conditionals with the `if-elseif-else` syntax, like this:\n\n```swift\nvar user:String = \"Bob\"\n\nif user == \"Alice\" \u0026\u0026 isActive\n{\n    print(\"Alice is active!\")\n}\nelse if user == \"Bob\" \u0026\u0026 !isActive\n{\n    print(\"Bob is lazy!\")\n}\nelse\n{\n    print(\"When none of the above are true...\")\n}\n```\n\nThe `\u0026\u0026` is the _Logical AND_ operator. You use it to create logical expressions that can be evaluated to `true` or `false`. Like this:\n\n```swift\nif user == \"Deep Thought\" || meaningOfLife == 42\n{\n    print(\"The user is Deep Thought, or the meaning of life is 42...\")\n} \n```\n\nOperators, like `\u0026\u0026`, have an order of _precedence_. This determines which operator has priority over another; which operator is evaluated before the other. Check this out:\n\n```swift\nlet a = 2 + 3 * 4\n// Output: 14\n```\n\nThe value of `a` is 14 and not 20, because multiplication precedes addition. A quick overview: `! * / + - \u0026\u0026 ||`. \n\nYou can change the order of operations with parentheses. Like this:\n\n```swift\nlet a = (2 + 3) * 4\n// Output: 20\n```\n\nThis groups the addition, which is now evaluated before the multiplication. Precedence rules are especially important when working with the logical `\u0026\u0026` (AND) and `||` (OR) operators. `\u0026\u0026` goes before `||`. Check this out:\n\n```swift\nlet isPresident = true\nlet threatLevel = 1\nlet officerRank = 1\n\nif threatLevel \u003e 5 \u0026\u0026 officerRank \u003e= 3 || isPresident {\n    print(\"(1) FIRE ROCKETS!!!\")\n}\n\nif threatLevel \u003e 5 \u0026\u0026 (officerRank \u003e= 3 || isPresident) {\n    print(\"(2) FIRE ROCKETS!!!\")\n}\n// Output: (1) FIRE ROCKETS!!!\n```\n\nNotice how the result of the above conditionals changes based on the parentheses, while their operators and operands stay the same.\n\n- In the first conditional, the rockets are fired because `isPresident` is `true` and the entire conditional evaluates to `(false \u0026\u0026 false -\u003e false) || true -\u003e false || true -\u003e true`.\n- In the second conditional, the rockets aren't fired even though `isPresident` is `true`. The entire conditional evaluates to `false \u0026\u0026 (false || true -\u003e true) -\u003e false \u0026\u0026 true -\u003e false`.\n\nSwift has a special operator, called the _ternary conditional operator_. It's coded as `a ? b : c`. If `a` is `true`, the expression returns `b`, and if `a` is `false`, the expression returns `c`. It's the equivalent of this:\n\n```swift\nif a {\n    b\n} else {\n    c\n}\n```\n\n### \u003ca name=\"loops\"\u003e\u003c/a\u003e Loops\n\nLoops repeat stuff. It's that easy. Like this:\n\n```swift\nfor i in 1...5 {\n    print(i)\n}\n// Output: 1 2 3 4 5\n```\n\nThis prints `1` to `5`, including `5`! You can also use the _half-open range operator_ `a..\u003cb` to loop from `a` to `b` _not including_ `b`. Like this:\n\n```swift\nfor i in 1..\u003c5 {\n    print(i)\n}\n// Output: 1 2 3 4\n```\n\nYou can use `continue` in a loop to skip to the next iteration, and `break` to quit looping altogether. Like this:\n\n```swift\nfor i in 0..\u003c10 \n{\n    if i.isMultiple(of: 2) {\n        continue\n    }\n\n    if i == 7 {\n        break\n    }\n\n    print(i)\n}\n// Output: 1 3 5\n```\n\nWhen you don't know how many times a loop needs to run _exactly_, you can use a `while` loop. A `while` loop keeps iterating as long as its expression is `true`.\n\n```swift\nvar steps = 42\n\nwhile steps \u003e 0 {\n    steps -= 9\n    print(steps)\n}\n// Output: 33 24 15 6 -3\n```\n\nA `while` loop will evaluate its condition _at the top_ of the loop, so before the next iteration runs. The `repeat-while` evaluates its condition _at the end_ of the loop. It'll always run the first iteration, before evaluating the loop condition.\n\n### \u003ca name=\"switch\"\u003e\u003c/a\u003e Switch\n\nA `switch` statement takes a value and compares it against one of several _cases_. It's similar to the `if-else if-else` conditional, and it's an elegant way of dealing with multiple states.\n\nAn example:\n\n```swift\nenum WeatherType {\n    case rain, clear, sunny, overcast, tsunami, earthquake, snow;\n}\n\nlet weather = WeatherType.sunny\n\nswitch weather \n{\n    case .rain:\n        print(\"Bring a raincoat!\")\n    case .clear, .sunny:\n        print(\"Don't forget your sunglasses.\")\n    case .overcast:\n        print(\"It's really depressing.\")\n    case .tsunami, .earthquake:\n        print(\"OH NO! BIG WAVE!\")\n    default:\n        print(\"Expect the best, prepare for the worst.\")\n}\n```\n\nIn Swift, `switch` statements don't have an implicit _fall-through_, but you can use `fallthrough` explicitly. Every case needs to have at least one line of code in it. You don't have to use a `break` explicitly to end a case.\n\nThe `switch` cases need to be _exhaustive_. For example, when working with an `enum`, you'll need to incorporate every value in the enumeration. You can also provide a `default` case, which is similar to `else` in a conditional.\n\nYou can also use Swift _ranges_ to match interval for numbers, use tuples to match partial values, and use Swift's `where` keyword to check for additional conditions.\n\n## \u003ca name=\"strings\"\u003e\u003c/a\u003e Strings\n\nStrings are pretty cool. Here's an example:\n\n```swift\nvar jobTitle: String = \"iOS App Developer\"\n```\n\nInside a string, you can use _string interpolation_ to string together multiple strings. Like this:\n\n```swift\nvar hello = \"Hello, \\(jobTitle)\"\n// Output: Hello, iOS App Developer\n```\n\nYou can also use the `+` addition operator to concatenate multiple strings:\n\n```swift\nlet a  = \"Never gonna\"\nlet b  = \"give you up\"\nlet rr = a + \" \" + b\n```\n\nYou can also turn an `Int` into a `String`:\n\n```swift\nlet number = 42\nlet numberAsString = \"\\(number)\"\n```\n\nAnd vice-versa:\n\n```swift\nlet number = \"42\"\nlet numberAsInt = Int(number)\n```\n\nYou can loop over the characters of a string like this:\n\n```swift\nlet text = \"Forty-two!\"\n\nfor char in text {\n    print(char)\n}\n```\n\nYou can get individual characters and character ranges by using _indices_, like this:\n\n```swift\nlet text = \"Forty-two!\"\ntext[text.startIndex] // F\ntext[text.index(before: text.endIndex)] // !\ntext[text.index(text.startIndex, offsetBy: 3)] // t\ntext[..\u003ctext.index(text.startIndex, offsetBy: 3)] // For\ntext[text.index(text.endIndex, offsetBy: -4)...] // two!\n```\n\nYou can trim all whitespace at the start and end of a string like this:\n\n```swift\nlet text = \"  Forty-two!  \"\nlet trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) // Forty-two!\n```\n\n## \u003ca name=\"optionals\"\u003e\u003c/a\u003e Optionals\n\n_Optionals_ can either be `nil` or contain a value. You **must** always _unwrap_ an optional before you can use it.\n\nThis is Bill. Bill is an optional.\n\n```swift\nvar bill: String? = nil\n```\n\nYou can unwrap `bill` in a number of ways. First, this is _optional binding_.\n\n```swift\nif let definiteBill = bill {\n    print(definiteBill)\n}\n```\n\nIn this example, you bind the non-optional value from `bill` to `definiteBill` _but only when `bill` is not `nil`_. It's like asking: \"Is it not `nil`?\" OK, if not, then assign it to this constant and execute that stuff between the squiggly brackets.\n\nYou can also use _force-unwrapping_ to unwrap an optional. Like this:\n\n```swift\nvar droid: String? = \"R2D2\"\n\nif droid != nil {\n    print(\"This is not the droid you're looking for: \\(droid!)\")\n}\n```\n\nSee how that `droid` is force-unwrapped with the exclamation mark `!`? You should keep in mind that if `droid` is `nil` when you force-unwrap it, your app will crash.\n\nYou can also use _optional chaining_ to work your way through a number of optionals. This saves you from coding too much optional binding blocks. Like this:\n\n```swift\nview?.button?.title = \"BOOYAH!\"\n```\n\nIn this code, `view`, `button` and `title` are all optionals. When `view` is `nil`, the code \"stops\" before `button`, so the `button` property is never accessed.\n\nOne last thing... the _nil-coalescing operator_. You can use it to provide a default value when an expression results in `nil`. Like this:\n\n```swift\nvar meaningOfLife = deepThought.think() ?? 42\n```\n\nSee that `??`. When `deepThought.think()` returns `nil`, the variable `meaningOfLife` is `42`. When that function returns a value, it's assigned to `meaningOfLife`.\n\n## \u003ca name=\"collections\"\u003e\u003c/a\u003e Collections\n\n### \u003ca name=\"arrays\"\u003e\u003c/a\u003e Arrays\n\nArrays are a collection type. Think of it as a variable that can hold multiple values, like a closet that can contain multiple drawers. Arrays always have _numerical_ index values. Arrays always contain elements of the same type.\n\n```swift\nvar hitchhikers = [\"Ford\", \"Arthur\", \"Zaphod\", \"Trillian\"]\n```\n\nYou can add items to the array:\n\n```swift\nhitchhikers += [\"Marvin\"]\n```\n\nYou can get items from the array with _subscript syntax_:\n\n```swift\nlet arthur = hitchhikers[1]\n```\n\nRemember that arrays are _zero-index_, so the index number of the first element is `0` (and not `1`).\n\nYou can iterate arrays, like this:\n\n```swift\nfor name in hitchhikers {\n    print(name)\n}\n```\n\nA helpful function on arrays is `enumerated()`. It lets you iterate index-value pairs, like this:\n\n```swift\nfor (index, name) in hitchhikers.enumerated() {\n    print(\"\\(index) = \\(name)\")\n}\n```\n\n### \u003ca name=\"dictionaries\"\u003e\u003c/a\u003e Dictionaries\n\nDictionaries are also collection types. The items in a dictionary consists of key-value pairs. Unlike arrays, you can set your own key type. Like this:\n\n```swift\nvar score = [\n    \"Fry\": 10,\n    \"Leela\": 29,\n    \"Bender\": 1,\n    \"Zoidberg\": 0\n]\n```\n\nWhat's the type of this dictionary? It's `[String: Int]`. Just like with arrays, you can use _subscript syntax_ to get the value for a key:\n\n```swift\nprint(score[\"Leela\"])\n// Output: 29\n```\n\nYou can add a key-value pair to a dictionary like this:\n\n```swift\nscore[\"Amy\"] = 9001\n```\n\nChange it like this:\n\n```swift\nscore[\"Bender\"] = -1\n```\n\nAnd remove it like this:\n\n```swift\nscore.removeValue(forKey: \"Zoidberg\")\n```\n\nYou can also iterate a dictionary, like this:\n\n```swift\nfor (name, points) in score\n{\n    print(\"\\(name) has \\(points) points\");\n}\n```\n\n### \u003ca name=\"sets\"\u003e\u003c/a\u003e Sets\n\n_Sets_ in Swift are similar to arrays and dictionaries. Just like arrays and dictionaries, the `Set` type is used to store multiple items of the same type in one collection.\n\nHere's an example:\n\n```swift\nvar fruit:Set = [\"apple\", \"banana\", \"strawberry\", \"jackfruit\"]\n```\n\nYou can add and remove items like this:\n\n```swift\nfruit.insert(\"pineapple\")\nfruit.remove(\"banana\")\n```\n\nSets are different from arrays and dictionaries, in these ways:\n\n- Sets don't have an order – they're literally unsorted\n- Every item in a set needs to be unique\n- Sets don't have indices or keys\n- Instead, a set's values need to be _hashable_\n- Because set items are hashable, you can search sets in _O(1)_ time\n\nHere's how you can quickly search a set:\n\n```swift\nlet movies:Set = [\"Rocky\", \"The Matrix\", \"Lord of the Rings\"]\n\nif movies.contains(\"Rocky\") {\n    print(\"Rocky is one of your favorite movies!\")\n}\n```\n\nSets are particularly useful for membership operations, to find out if sets have items in common for example. We can make a union of sets, subtract sets, intersect them, and find their differences.\n\nConsider the following Italian coffees and their ingredients:\n\n```swift\nlet cappuccino:Set = [\"espresso\", \"milk\", \"milk foam\"]\nlet americano:Set  = [\"espresso\", \"water\"]\nlet machiato:Set   = [\"espresso\", \"milk foam\"]\nlet latte:Set      = [\"espresso\", \"milk\"]\n```\n\nCan we find the **union** (add items) of two coffees?\n\n```swift\nmachiato.union(latte)\n// [\"espresso\", \"milk foam\", \"milk\"]\n```\n\nCan we **subtract** one coffee from another?\n\n```swift\ncappuccino.subtracting(americano)\n// [\"milk foam\", \"milk\"]\n```\n\nCan we find the **intersection** (shared items) of two coffees?\n\n```swift\nlatte.intersection(cappuccino)\n// [\"espresso\", \"milk\"]\n```\n\nCan we find the **difference** between two coffees?\n\n```swift\nlatte.symmetricDifference(americano)\n// [\"milk\", \"water\"]\n```\n\n## \u003ca name=\"closures\"\u003e\u003c/a\u003e Closures\n\nWith _closures_ you can pass around blocks of code, like functions, as if they are variables. You use them, for example, by passing a callback to a lengthy task. When the task ends, the callback – a closure – is executed.\n\nYou define a closure like this:\n\n```swift\nlet authenticate = { (name: String, userLevel: Int) -\u003e Bool in\n    return (name == \"Bob\" || name == \"Alice\") \u0026\u0026 userLevel \u003e 3\n}\n```\n\nYou call the closure like this:\n\n```swift\nauthenticate(\"Bob\", 7)\n```\n\nClosures have a type, that reflect the closure's parameters and its return type. The type of the closure for `authenticate` is `(String, Int) -\u003e Bool`.\n\nIf we had a user interface for authenticating a user, then we could pass the closure as a callback like this:\n\n```swift\nlet loginVC = MyLoginViewController(withAuthCallback: authenticate)\n```\n\nYou always write a closure inside squiggly brackets `{ }`. Within the closure, you can declare zero, one or more parameters (with types), and optionally, a return type, followed by `in`. \n\nClosure syntax is flexible, and has a few shorthands, which means you can leave out parts of the closure's declaration to make the code more concise.\n\nFor example, the closure in this code:\n\n```swift\nlet names = [\"Zaphod\", \"Trillian\", \"Ford\", \"Arthur\", \"Marvin\"]\nlet sortedNames = names.sorted(by: \u003c)\n```\n\n... is the same as this code:\n\n```swift\nnames.sorted(by: { (s1: String, s2: String) -\u003e Bool in\n    return s1 \u003c s2\n})\n```\n\n... and that's the same as this, too:\n\n```swift\nnames.sorted(by: { s1, s2 in s1 \u003c s2 } )\n```\n\n... and even this, too:\n\n```swift\nnames.sorted { $0 \u003c $1 }\n```\n\nAnother use case for closures is multi-threading with Grand Central Dispatch. Like this:\n\n```swift\nDispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(60)) {  \n    // Dodge this!  \n}\n```\n\nIn the above example, the last argument of `asyncAfter(deadline:execute:)` is a closure. It uses the _trailing closure_ syntax. When a closure is the last argument of a function call, you can write it after the function call parentheses and omit the argument label.\n\n## \u003ca name=\"guard-defer\"\u003e\u003c/a\u003e Guard and Defer\n\n### \u003ca name=\"guard\"\u003e\u003c/a\u003e Guard\n\nThe `guard` statement helps you to return functions early. It's a conditional, and when it isn't met you need to exit the function with `return`.\n\nLike this:\n\n```swift\nfunc loadTweets(forUserID userID: Int) \n{\n    guard userID \u003e 0 else {\n        return\n    }\n\n    // Load the tweets...\n}\n```\n\nYou can read that as: _\"Guard that the User ID is greater than zero, or else, exit this function\"_. Guard is especially powerful when you have multiple conditions that should return the function.\n\nGuard blocks always need to exit its enclosing scope, i.e. transfer control outside of the scope, by using `return`, `throw`, `break` or `continue`.\n\nYou can also combine `guard` and `if let` (optional binding) into `guard let`. This checks if the given expression is not `nil`, and assigns it to a constant. When the expression is `nil`, the `else` clause of `guard` is executed.\n\n```swift\nguard let user = object?.user else {\n    return\n}\n```\n\nYou can now use the `user` constant in the rest of the scope, below the `guard let` block.\n\n### \u003ca name=\"defer\"\u003e\u003c/a\u003e Defer\n\nWith `defer` you can define a code block that's executed when your function returns. The `defer` statement is similar to `guard`, because it also helps with the flow of your code. \n\nLike this:\n\n```swift\nfunc saveFile(withData data: Data) {\n\n    let filePointer = openFile(\"../example.txt\")\n\n    defer {\n        closeFile(filePointer)\n    }\n\n    if filePointer.size \u003e 0 {\n        return\n    }\n\n    if data.size \u003e 512 {\n        return\n    }\n\n    writeFile(filePointer, withData: data)\n}\n```\n\nIn the example code you're opening a file and writing some data to it. As a rule, you need to close the file pointer before exiting the function. \n\nThe file isn't written to when two conditions aren't met. You have to close the file at those points. Without the `defer` statement, you would have written `closeFile(_:)` twice. \n\nThanks to `defer`, the file is always closed when the function returns.\n\n## \u003ca name=\"generics\"\u003e\u003c/a\u003e Generics\n\nIn Swift your variables are _strong typed_. When you set the type of animals your farm can contain to `Duck`, you can't change that later on. With _generics_ however, you can!\n\nLike this:\n\n```swift\nfunc insertAnimal\u003cT\u003e(_ animal: T, inFarm farm: Farm) \n{\n    // Insert `animal` in `farm`\n}\n```\n\nThis is a _generic function_. It uses a _placeholder type_ called `T` instead of an actual type name, like `String`. \n\nIf you want to insert ducks, cows, birds and chickens in your farm, you can now do that with one function instead of 4.\n\n## \u003ca name=\"tuples\"\u003e\u003c/a\u003e Tuples\n\nWith _tuples_ you get two (or more) variables for one. They help you structure your code better. Like this:\n\n```swift\nlet coffee = (\"Cappuccino\", 3.99)\n```\n\nYou can now get the price of the coffee like this:\n\n```swift\nlet (name, price) = coffee\nprint(price)\n// Output: 3.99\n```\n\nWhen you need just the name, you can do this:\n\n```swift\nlet (name, _) = coffee\nprint(name)\n// Output: Cappuccino\n```\n\nYou can also name the elements of a tuple, like this:\n\n```swift\nlet flight = (code: \"XJ601\", heading: \"North\", passengers: 216)\nprint(flight.heading) \n// Output: North\n```\n\n## \u003ca name=\"enums\"\u003e\u003c/a\u003e Enumerations\n\nWith enumerations, also known as enums, you can organize groups of values that are related. Here's an example:\n\n```swift\nenum Compass {\n    case north\n    case east\n    case south\n    case west\n}\n```\n\nHere's how you use them:\n\n```swift\nlet direction: Compass = .south\n```\n\nEnums and the `switch` statement are a powerful couple. Here's an example:\n\n```swift\nenum Emotion {\n    case happy, sad, angry, scared, surprised\n}\n\nswitch robot.mood {\ncase .angry:\n    robot.destroyAllHumans()\ncase .sad:\n    robot.cry()\ncase .happy:\n    robot.play(\"happy.mp3\")\ncase default:\n    print(\"Error: emotion not supported.\")\n}\n```\n\nYou can also assign raw values to enums, by using existing Swift types like `String`. Here's an example:\n\n```swift\nenum Flavor:String {\n    case vanilla = \"vanilla\"\n    case strawberry = \"strawberry\"\n    case chocolate = \"chocolate\"\n}\n```\n\nWith this approach, you can get the string value for an enum like this:\n\n```swift\nlet icecream = Flavor.vanilla\nprint(icecream.rawValue)\n// Output: vanilla\n```\n\nYou can now also use a string to create an enum, like this:\n\n```swift\nlet icecream = Flavor(rawValue: \"vanilla\")\nprint(icecream)\n// Output: Optional(Flavor.vanilla)\n```\n\nYou can also associate values with individual cases of an enumeration, like this:\n\n```swift\nenum Item {\n    case weapon(Int, Int)\n    case food(Int)\n    case armor(Int, Int, Double)\n}\n```\n\nYou can now use the enumeration's associated values, like this:\n\n```swift\nfunc use(item: Item)\n{\n    switch item {\n    case .weapon(let hitPoints, _):\n        player.attack(hitPoints)\n    case .food(let health):\n        player.health += health\n    case .armor(let damageThreshold, let weight, let condition):\n        player.damageThreshold = Double(damageThreshold) * condition\n    }\n}\n```\n\nIn the above code, we're using `hitPoints` to \"attack\" in case `item` is the enum type `weapon(Int, Int)`. This way you can associate additional values with an enum case.\n\n## \u003ca name=\"error-handling\"\u003e\u003c/a\u003e Error Handling\n\nErrors in Swift can be thrown, and should be caught. You can define an error type like this:\n\n```swift\nenum CreditCardError: Error {\n    case insufficientFunds\n    case issuerDeclined\n    case invalidCVC\n}\n```\n\nWhen you code a function that can throw errors, you have to mark its function definition with `throws`. Like this:\n\n```swift\nfunc processPayment(creditcard: String) throws {\n    ...\n```\n\nInside the function, you can then throw an error like this:\n\n```swift\nthrow CreditCardError.insufficientFunds\n```\n\nWhen you _use_ a function that can throw errors, you have to wrap it in a `do-try-catch` block. Like this:\n\n```swift\ndo {\n    try processPayment(creditcard: \"1234.1234\")\n}\ncatch {\n    print(error)\n}\n```\n\nIn the example above, the `processPayment(creditcard:)` function is marked with the `try` keyword. When an error occurs, the `catch` block is executed.\n\n## \u003ca name=\"commenting\"\u003e\u003c/a\u003e Commenting\n\nThere are 3 types of comments:\n\n**1. Documentary**: Describes the history and development of the file. Their core purpose is to improve code maintainability. Most notable examples are:\n\n- Filename\n- Project name\n- Creation and modification dates\n- Author\n- Copyright\n- Version\n- History of changes\n- Dependencies\n\nDocumentary comments are wordy and error-prone if typed manually. Capture only those details, which are not available to version controls tools like git.\n\nWe are dealing with documentary comments every day, often without realizing it:\n\n```swift\n//\n//  AppDelegate.swift\n//\n//  Created by John Doe on 28/7/20.\n//  Copyright © 2020 Acme Inc. All rights reserved.\n//\n```\n\n**2. Functional**: Adds information and special directives to the development process. Most notable examples in Swift are:\n\n- Diagnostic directives: `#warning`, `#error`\n- Annotations: `TODO`, `MARK`, `FIXME`, and 3rd-party-specific like `swiftlint:disable`\n- Notes about who fixed what bug when, e.g. \"Bugfix: This is how I fixed it. -VABU\"\n- Performance improvement notes\n\n**3. Explanatory**: Summarizes code or explains the programmer's intent. Explanatory comments must answer the question _why_ instead of _what_.\n\nExplanatory comments make the most sense in these scenarios:\n\n- Code does not fit project conventions\n- Algorithm description: name, complexity, documentation\n- Complex regular expressions\n- Workarounds and hacks\n\n### Comment Syntax\n\nSwift comments can be written in two formats:\n\nEach line is preceded by a double slash `//`\n\n```swift\n// \u003c#Description#\u003e\n//\n// - Parameter value: \u003c#value description#\u003e\n// - Returns: \u003c#return value description#\u003e\nfunc isOdd(_ value: Int) -\u003e Bool {\n    return abs(value) % 2 == 1\n}\n```\n\nJavadoc-style block comments `/* … */`\n\n```swift\n/* \u003c#Description#\u003e\n\n  - Parameter value: \u003c#value description#\u003e\n  - Returns: \u003c#return value description#\u003e\n*/\nfunc isOdd(_ value: Int) -\u003e Bool {\n    return abs(value) % 2 == 1\n}\n```\n\n## \u003ca name=\"resources\"\u003e\u003c/a\u003e Resources\n\nNo cheatsheet is complete without a list of resources with more information. Wanna see how deep the rabbit hole really goes?\n\n- [Swift Language Guide](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html)\n- [Swift Evolution](https://apple.github.io/swift-evolution/)\n- [Swift Standard Library](https://developer.apple.com/documentation/swift)\n- [Apple Developer Documentation](https://developer.apple.com/documentation/)\n- [https://github.com/vsouza/awesome-ios](https://github.com/vsouza/awesome-ios)\n- [https://github.com/matteocrippa/awesome-swift](https://github.com/matteocrippa/awesome-swift)\n- [http://online.swiftplayground.run/](http://online.swiftplayground.run/)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freinder42%2FSwiftCheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freinder42%2FSwiftCheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freinder42%2FSwiftCheatsheet/lists"}