{"id":18060341,"url":"https://github.com/unbug/sj","last_synced_at":"2025-04-05T12:15:00.292Z","repository":{"id":47301670,"uuid":"138035780","full_name":"unbug/sj","owner":"unbug","description":"Swift and JavaScript comparison snippets","archived":false,"fork":false,"pushed_at":"2019-05-10T12:37:50.000Z","size":1022,"stargazers_count":14,"open_issues_count":1,"forks_count":2,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-02-10T23:35:11.396Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/unbug.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-06-20T13:22:12.000Z","updated_at":"2023-03-08T04:09:00.000Z","dependencies_parsed_at":"2022-09-06T07:11:20.803Z","dependency_job_id":null,"html_url":"https://github.com/unbug/sj","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unbug%2Fsj","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unbug%2Fsj/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unbug%2Fsj/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/unbug%2Fsj/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/unbug","download_url":"https://codeload.github.com/unbug/sj/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247332596,"owners_count":20921854,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2024-10-31T04:07:49.660Z","updated_at":"2025-04-05T12:15:00.268Z","avatar_url":"https://github.com/unbug.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg src=\"https://user-images.githubusercontent.com/799578/41671640-51642072-74ea-11e8-8bf2-7588062eed70.png\" width=\"300\"\u003e\n\n# Swift and JavaScript comparison snippets\n\n**Issue and pull request are welcome, please!**\n\n# Table of content\n- [The Basics](#the-basics)\n- [Basic Operators](#basic-operators)\n- [Strings and Characters](#strings-and-characters)\n- [Collection Types](#collection-types)\n- [Control Flow](#control-flow)\n- [Functions](#functions)\n- [Closures](#closures)\n- [Classes](#classes)\n- [Inheritance](#inheritance)\n\n\u003e This table of content is from [The swift programming language guide](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html)\n\n## The Basics\n### Constants and Variables\nSwift\n\n```swift\n// declare a constant \nlet maximumNumberOfLoginAttempts = 10\n\n// declare a variable\nvar currentLoginAttempt = 0\n\n// declare multiple constants or multiple variables on a single line, separated by commas\nvar x = 0.0, y = 0.0, z = 0.0\n```\n\nJavaScript\n```javascript\n// declare a constant \nconst maximumNumberOfLoginAttempts = 10\n\n// declare a variable\nvar currentLoginAttempt = 0 \n// or \nlet currentLoginAttempt = 0\n\n// declare multiple constants or multiple variables on a single line, separated by commas\nvar x = 0.0, y = 0.0, z = 0.0\n\n```\n\n### Comments\nSwift\n```swift\n// This is a comment.\n\n/* This is also a comment\nbut is written over multiple lines. */\n\n```\n\nJavaScript\n```javascript\n// This is a comment.\n\n/* This is also a comment\nbut is written over multiple lines. */\n\n```\n\n### Numeric Type Conversion\n\nSwift\n```swift\nlet pi = 3.14159\n// Integer and Floating-Point Conversion\nlet integerPi = Int(pi)\n```\n\nJavaScript\n```javascript\nconst pi = 3.14159\n// Integer and Floating-Point Conversion\nconst integerPi = parseInt(pi)\n```\n\n### Booleans\nSwift\n```swift\nlet orangesAreOrange = true\nlet turnipsAreDelicious = false\n\nif turnipsAreDelicious {\n    print(\"Mmm, tasty turnips!\")\n} else {\n    print(\"Eww, turnips are horrible.\")\n}\n```\n\nJavaScript\n```javascript\nconst orangesAreOrange = true\nconst turnipsAreDelicious = false\n\nif (turnipsAreDelicious) {\n    console.log(\"Mmm, tasty turnips!\")\n} else {\n    console.log(\"Eww, turnips are horrible.\")\n}\n```\n\n### Error Handling\nSwift\n```swift\nfunc canThrowAnError() throws {\n    // this function may or may not throw an error\n}\ndo {\n    try canThrowAnError()\n    // no error was thrown\n} catch {\n    // an error was thrown\n}\n\n```\n\nJavaScript\n```javascript\nfunction canThrowAnError() {\n    // this function may or may not throw an error\n}\ntry {\n    canThrowAnError()\n    // no error was thrown\n} catch (e) {\n    // an error was thrown\n}\n```\n## Basic Operators\n### Assignment Operator\nSwift\n```swift\nlet b = 10\nvar a = 5\na = b\n\n// decomposed tuple with multiple values into multiple variables\nlet (x, y) = (1, 2)\nprint(\"x = \\(x), y = \\(y)\") // x = 1, y = 2\n```\n\nJavaScript\n```javascript\nlet b = 10\nvar a = 5\na = b\n\n// object matching with destructuring assignment\nconst {x, y} = {x:1, y:2}\nconsole.log(`x = ${x}, y = ${y}`) // x = 1, y = 2\n// or array matching with destructuring assignment\nconst [x, y] = [1, 2]\nconsole.log(`x = ${x}, y = ${y}`) // x = 1, y = 2\n```\n### Arithmetic Operators\n- Addition (+)\n- Subtraction (-)\n- Multiplication (*)\n- Division (/)\n\nSwift\n```swift\n1 + 2       // equals 3\n5 - 3       // equals 2\n2 * 3       // equals 6\n10.0 / 2.5  // equals 4.0\n\"hello, \" + \"world\"  // equals \"hello, world\"\n```\n\nJavaScript\n```javascript\n1 + 2       // equals 3\n5 - 3       // equals 2\n2 * 3       // equals 6\n10.0 / 2.5  // equals 4\n\"hello, \" + \"world\"  // equals \"hello, world\"\n```\n### Remainder Operator\nSwift\n```swift\n9 % 4    // equals 1\n-9 % 4   // equals -1\n```\n\nJavaScript\n```javascript\n9 % 4    // equals 1\n-9 % 4   // equals -1\n```\n### Unary Minus/Plus Operator\nSwift\n```swift\nlet three = 3\nlet minusThree = -three       // minusThree equals -3\nlet plusThree = -minusThree   // plusThree equals 3, or \"minus minus three\"\n\nlet minusSix = -6\nlet alsoMinusSix = +minusSix  // alsoMinusSix equals -6\n```\n\nJavaScript\n```javascript\nconst three = 3\nconst minusThree = -three       // minusThree equals -3\nconst plusThree = -minusThree   // plusThree equals 3, or \"minus minus three\"\n\nconst minusSix = -6\nconst alsoMinusSix = +minusSix  // alsoMinusSix equals -6\n```\n### Compound Assignment Operators\nSwift\n```swift\nvar a = 1\na += 2 // a is now equal to 3\n```\n\nJavaScript\n```javascript\nlet a = 1\na += 2 // a is now equal to 3\n```\n### Comparison Operators\n- Equal to (a == b)\n- Not equal to (a != b)\n- Greater than (a \u003e b)\n- Less than (a \u003c b)\n- Greater than or equal to (a \u003e= b)\n- Less than or equal to (a \u003c= b)\n- Identity operators, refer to the same object instance (a === b)\n- Identity operators, not refer to the same object instance (a !== b)\n\nSwift\n```swift\n1 == 1   // true because 1 is equal to 1\n2 != 1   // true because 2 is not equal to 1\n2 \u003e 1    // true because 2 is greater than 1\n1 \u003c 2    // true because 1 is less than 2\n1 \u003e= 1   // true because 1 is greater than or equal to 1\n2 \u003c= 1   // false because 2 is not less than or equal to 1\n\nlet name = \"world\"\nif name == \"world\" {\n    print(\"hello, world\")\n} else {\n    print(\"I'm sorry \\(name), but I don't recognize you\")\n}\n// Prints \"hello, world\", because name is indeed equal to \"world\".\n\nlet p1 = Person();\nlet p2 = Person();\np1 === p2 // false\np1 !== p2 // true\n\n```\n\nJavaScript\n```javascript\n1 == 1   // true because 1 is equal to 1\n2 != 1   // true because 2 is not equal to 1\n2 \u003e 1    // true because 2 is greater than 1\n1 \u003c 2    // true because 1 is less than 2\n1 \u003e= 1   // true because 1 is greater than or equal to 1\n2 \u003c= 1   // false because 2 is not less than or equal to 1\n\nconst name = \"world\"\nif (name == \"world\") {\n    console.log(\"hello, world\")\n} else {\n    console.log(`I'm sorry ${name}, but I don't recognize you`)\n}\n// Prints \"hello, world\", because name is indeed equal to \"world\".\n\nconst p1 = new Person();\nconst p2 = new Person();\np1 === p2 // false\np1 !== p2 // true\n```\n### Ternary Conditional Operator\nSwift\n```swift\nlet contentHeight = 40\nlet hasHeader = true\nlet rowHeight = contentHeight + (hasHeader ? 50 : 20)\n// rowHeight is equal to 90\n```\n\nJavaScript\n```javascript\nconst contentHeight = 40\nconst hasHeader = true\nconst rowHeight = contentHeight + (hasHeader ? 50 : 20)\n// rowHeight is equal to 90\n```\n### Logical Operators\n- Logical NOT (!a)\n- Logical AND (a \u0026\u0026 b)\n- Logical OR (a || b)\n\nSwift\n```swift\nlet allowedEntry = false\nif !allowedEntry {\n    print(\"ACCESS DENIED\")\n}\n// Prints \"ACCESS DENIED\"\n\nlet hasDoorKey = false\nlet knowsOverridePassword = true\nlet hasDoorKey = false\nlet knowsOverridePassword = true\nif enteredDoorCode \u0026\u0026 passedRetinaScan || hasDoorKey || knowsOverridePassword {\n    print(\"Welcome!\")\n} else {\n    print(\"ACCESS DENIED\")\n}\n// Prints \"Welcome!\"\n```\n\nJavaScript\n```javascript\nconst allowedEntry = false\nif (!allowedEntry) {\n    console.log(\"ACCESS DENIED\")\n}\n// Prints \"ACCESS DENIED\"\n\nconst hasDoorKey = false\nconst knowsOverridePassword = true\nconst hasDoorKey = false\nconst knowsOverridePassword = true\nif (enteredDoorCode \u0026\u0026 passedRetinaScan || hasDoorKey || knowsOverridePassword) {\n    console.log(\"Welcome!\")\n} else {\n    console.log(\"ACCESS DENIED\")\n}\n// Prints \"Welcome!\"\n```\n\n## Strings and Characters\n### String Literals\nSwift\n```swift\nlet someString = \"Some string literal value\"\n\n// Multiline String Literals with three double quotation marks (\"\"\")\nlet quotation = \"\"\"\nThe White Rabbit put on his spectacles.  \"Where shall I begin,\nplease your Majesty?\" he asked.\n\n\"Begin at the beginning,\" the King said gravely, \"and go on\ntill you come to the end; then stop.\"\n\"\"\"\n\n// String Mutability\nvar variableString = \"Horse\"\nvariableString += \" and carriage\"\n// variableString is now \"Horse and carriage\"\n\nlet constantString = \"Highlander\"\nconstantString += \" and another Highlander\"\n// this reports a compile-time error - a constant string cannot be modified\n```\n\nJavaScript\n```javascript\nconst someString = \"Some string literal value\"\n\n// Multiline String Literals back-tick (` `) \nconst quotation = `\nThe White Rabbit put on his spectacles.  \"Where shall I begin,\nplease your Majesty?\" he asked.\n\n\"Begin at the beginning,\" the King said gravely, \"and go on\ntill you come to the end; then stop.\"\n`\n\n// String Mutability\nlet variableString = \"Horse\"\nvariableString += \" and carriage\"\n// variableString is now \"Horse and carriage\"\n\nconst constantString = \"Highlander\"\nconstantString += \" and another Highlander\"\n// this reports a compile-time error - a constant string cannot be modified\n```\n\n### String Interpolation\nSwift\n```swift\n// insert values into the string literal is wrapped in a pair of parentheses, prefixed by a backslash (\\)\nlet multiplier = 3\nlet message = \"\\(multiplier) times 2.5 is \\(Double(multiplier) * 2.5)\"\n// message is \"3 times 2.5 is 7.5\"\n```\n\nJavaScript\n```javascript\nconst multiplier = 3\nconst message = `${multiplier} times 2.5 is ${multiplier * 2.5}`\n// message is \"3 times 2.5 is 7.5\"\n```\n\n### Accessing and Modifying a String\nSwift\n```swift\n// String Indices\nlet greeting = \"Guten Tag!\"\ngreeting[greeting.startIndex]\n// G\ngreeting[greeting.index(before: greeting.endIndex)]\n// !\ngreeting[greeting.index(after: greeting.startIndex)]\n// u\n\n\n// Inserting and Removing\nvar welcome = \"hello\"\nwelcome.insert(\"!\", at: welcome.endIndex)\n// welcome now equals \"hello!\"\n\nwelcome.insert(contentsOf: \" there\", at: welcome.index(before: welcome.endIndex))\n// welcome now equals \"hello there!\"\n\nwelcome.remove(at: welcome.index(before: welcome.endIndex))\n// welcome now equals \"hello there\"\n\nlet range = welcome.index(welcome.endIndex, offsetBy: -6)..\u003cwelcome.endIndex\nwelcome.removeSubrange(range)\n// welcome now equals \"hello\"\n```\n\nJavaScript\n```javascript\nconst greeting = \"Guten Tag!\"\ngreeting.slice(0, 1)\n// G\ngreeting.slice(-1)\n// !\ngreeting.substr(1, 1)\n// u\n\n// Inserting and Removing\nlet welcome = \"hello\"\nwelcome += \"!\"\n// welcome now equals \"hello!\"\n\nwelcome = welcome.substr(0, welcome.length - 1) + \" there\" + welcome.slice(-1)\n// welcome now equals \"hello there!\"\n\nwelcome.substr(0, welcome.length - 1)\n// welcome now equals \"hello there\"\n\nlet index = welcome.indexOf(' ');\nwelcome.slice(0, index)\n// welcome now equals \"hello\"\n```\n\n## Collection Types\n### Mutability of Collections: Arrays\nSwift\n```swift\n// creata an empty array\nvar someInts = [Int]()\nprint(\"someInts is of type [Int] with \\(someInts.count) items.\")\n// Prints \"someInts is of type [Int] with 0 items.\"\n\n// Creating an Array with a Default Value\nvar threeDoubles = Array(repeating: 0.0, count: 3)\n// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]\nvar anotherThreeDoubles = Array(repeating: 2.5, count: 3)\n// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]\n\nvar sixDoubles = threeDoubles + anotherThreeDoubles\n// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]\n\n\n// Creating an Array with an Array Literal\nvar shoppingList: [String] = [\"Eggs\", \"Milk\"]\n// shoppingList has been initialized with two initial items\n\n\n// Accessing and Modifying an Array\nif shoppingList.isEmpty {\n    print(\"The shopping list is empty.\")\n} else {\n    print(\"The shopping list is not empty.\")\n}\n// Prints \"The shopping list is not empty.\"\nshoppingList.append(\"Flour\")\n// shoppingList now contains 3 items, and someone is making pancakes\nshoppingList += [\"Baking Powder\"]\n// shoppingList now contains 4 items\nshoppingList += [\"Chocolate Spread\", \"Cheese\", \"Butter\"]\n// shoppingList now contains 7 items\nvar firstItem = shoppingList[0]\n\n// firstItem is equal to \"Eggs\"\nshoppingList[0] = \"Six eggs\"\n// the first item in the list is now equal to \"Six eggs\" rather than \"Eggs\"\n\nshoppingList[4...6] = [\"Bananas\", \"Apples\"]\n// shoppingList now contains 6 items\n\nshoppingList.insert(\"Maple Syrup\", at: 0)\n// shoppingList now contains 7 items\n// \"Maple Syrup\" is now the first item in the list\n\nlet mapleSyrup = shoppingList.remove(at: 0)\n// the item that was at index 0 has just been removed\n// shoppingList now contains 6 items, and no Maple Syrup\n// the mapleSyrup constant is now equal to the removed \"Maple Syrup\" string\n\nlet apples = shoppingList.removeLast()\n// the last item in the array has just been removed\n// shoppingList now contains 5 items, and no apples\n// the apples constant is now equal to the removed \"Apples\" string\n\n\n// Iterating Over an Array\nfor item in shoppingList {\n    print(item)\n}\n// Six eggs\n// Milk\n// Flour\n// Baking Powder\n// Bananas\n\nfor (index, value) in shoppingList.enumerated() {\n    print(\"Item \\(index + 1): \\(value)\")\n}\n// Item 1: Six eggs\n// Item 2: Milk\n// Item 3: Flour\n// Item 4: Baking Powder\n// Item 5: Bananas\n```\n\nJavaScript\n```javascript\n// creata an empty array\nlet someInts = new Array()\nconsole.log(`someInts is an array with ${someInts.length} items.`)\n// Prints \"someInts is an array with 0 items.\"\n\n// Creating an Array with a Default Value\nlet threeDoubles = [0.0, 0.0, 0.0]\n// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]\nlet anotherThreeDoubles = [2.5, 2.5, 2.5]\n// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]\n\nlet sixDoubles = [...threeDoubles, ...anotherThreeDoubles]\n// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]\n\n\n// Creating an Array with an Array Literal\nlet shoppingList = [\"Eggs\", \"Milk\"]\n// shoppingList has been initialized with two initial items\n\n\n// Accessing and Modifying an Array\nif (shoppingList.length === 0) {\n    console.log(\"The shopping list is empty.\")\n} else {\n    console.log(\"The shopping list is not empty.\")\n}\n// Prints \"The shopping list is not empty.\"\nshoppingList.push(\"Flour\")\n// shoppingList now contains 3 items, and someone is making pancakes\nshoppingList = shoppingList.concat([\"Baking Powder\"])\n// shoppingList now contains 4 items\nshoppingList = [...shoppingList, \"Chocolate Spread\", \"Cheese\", \"Butter\"]\n// shoppingList now contains 7 items\nlet firstItem = shoppingList[0]\n// firstItem is equal to \"Eggs\"\nshoppingList[0] = \"Six eggs\"\n// the first item in the list is now equal to \"Six eggs\" rather than \"Eggs\"\n\nshoppingList.splice(4, 3, \"Bananas\", \"Apples\")\n// shoppingList now contains 6 items\n\nshoppingList.unshift(\"Maple Syrup\")\n// shoppingList now contains 7 items\n// \"Maple Syrup\" is now the first item in the list\n\nlet mapleSyrup = shoppingList.shift()\n// the item that was at index 0 has just been removed\n// shoppingList now contains 6 items, and no Maple Syrup\n// the mapleSyrup constant is now equal to the removed \"Maple Syrup\" string\n\nlet apples = shoppingList.pop()\n// the last item in the array has just been removed\n// shoppingList now contains 5 items, and no apples\n// the apples constant is now equal to the removed \"Apples\" string\n\n\n// Iterating Over an Array\nshoppingList.forEach((item =\u003e {\n    console.log(item)\n})\n// Six eggs\n// Milk\n// Flour\n// Baking Powder\n// Bananas\n\nshoppingList.forEach(((item, index) =\u003e {\n    console.log(`Item ${index + 1}: ${value}`)\n})\n// Item 1: Six eggs\n// Item 2: Milk\n// Item 3: Flour\n// Item 4: Baking Powder\n// Item 5: Bananas\n```\n### Sets\nSwift\n```swift\n// Creating and Initializing an Empty Set\nvar letters = Set\u003cCharacter\u003e()\nprint(\"letters is of type Set\u003cCharacter\u003e with \\(letters.count) items.\")\n// Prints \"letters is of type Set\u003cCharacter\u003e with 0 items.\"\nvar favoriteGenres: Set\u003cString\u003e = [\"Rock\", \"Classical\", \"Hip hop\"]\n// favoriteGenres has been initialized with three initial items\n\n\n// Accessing and Modifying a Set\nprint(\"I have \\(favoriteGenres.count) favorite music genres.\")\n// Prints \"I have 3 favorite music genres.\"\n\nif favoriteGenres.isEmpty {\n    print(\"As far as music goes, I'm not picky.\")\n} else {\n    print(\"I have particular music preferences.\")\n}\n// Prints \"I have particular music preferences.\"\n\nfavoriteGenres.insert(\"Jazz\")\n// favoriteGenres now contains 4 items\n\nif let removedGenre = favoriteGenres.remove(\"Rock\") {\n    print(\"\\(removedGenre)? I'm over it.\")\n} else {\n    print(\"I never much cared for that.\")\n}\n// Prints \"Rock? I'm over it.\"\n\nif favoriteGenres.contains(\"Funk\") {\n    print(\"I get up on the good foot.\")\n} else {\n    print(\"It's too funky in here.\")\n}\n// Prints \"It's too funky in here.\"\n\n\n// Iterating Over a Set\nfor genre in favoriteGenres {\n    print(\"\\(genre)\")\n}\n// Classical\n// Jazz\n// Hip hop\n```\n\nJavaScript\n```javascript\n// Creating and Initializing an Empty Set\nlet letters = new Set()\nconsole.log(`letters is of type Set with ${letters.size} items.`)\n// Prints \"letters is of type Set with 0 items.\"\nlet favoriteGenres = new set([\"Rock\", \"Classical\", \"Hip hop\"])\n// favoriteGenres has been initialized with three initial items\n\n\n// Accessing and Modifying a Set\nconsole.log(`I have ${favoriteGenres.size} favorite music genres.`)\n// Prints \"I have 3 favorite music genres.\"\n\nif (favoriteGenres.size == 0) {\n    console.log(\"As far as music goes, I'm not picky.\")\n} else {\n    console.log(\"I have particular music preferences.\")\n}\n// Prints \"I have particular music preferences.\"\n\nfavoriteGenres.add(\"Jazz\")\n// favoriteGenres now contains 4 items\nconst removedGenre = favoriteGenres.delete(\"Rock\")\nif (removedGenre) {\n    console.log(`${removedGenre}? I'm over it.`)\n} else {\n    console.log(\"I never much cared for that.\")\n}\n// Prints \"Rock? I'm over it.\"\n\nif (favoriteGenres.has(\"Funk\")) {\n    console.log(\"I get up on the good foot.\")\n} else {\n    console.log(\"It's too funky in here.\")\n}\n// Prints \"It's too funky in here.\"\n\n\n// Iterating Over a Set\nfavoriteGenres.forEach(genre =\u003e {\n    console.log(genre);\n})\n// Classical\n// Jazz\n// Hip hop\n```\n\n### Dictionaries\nSwift\n```swift\n// Creating an Empty Dictionary\nvar namesOfIntegers = [Int: String]()\n// namesOfIntegers is an empty [Int: String] dictionary\nnamesOfIntegers[16] = \"sixteen\"\n// namesOfIntegers now contains 1 key-value pair\nnamesOfIntegers = [:]\n// namesOfIntegers is once again an empty dictionary of type [Int: String]\n\n\n// Creating a Dictionary with a Dictionary Literal\nvar airports: [String: String] = [\"YYZ\": \"Toronto Pearson\", \"DUB\": \"Dublin\"]\n\n\n// Accessing and Modifying a Dictionary\nprint(\"The airports dictionary contains \\(airports.count) items.\")\n// Prints \"The airports dictionary contains 2 items.\"\n\nif airports.isEmpty {\n    print(\"The airports dictionary is empty.\")\n} else {\n    print(\"The airports dictionary is not empty.\")\n}\n// Prints \"The airports dictionary is not empty.\"\n\nairports[\"LHR\"] = \"London\"\n// the airports dictionary now contains 3 items\n\nairports[\"LHR\"] = \"London Heathrow\"\n// the value for \"LHR\" has been changed to \"London Heathrow\"\n\nif let oldValue = airports.updateValue(\"Dublin Airport\", forKey: \"DUB\") {\n    print(\"The old value for DUB was \\(oldValue).\")\n}\n// Prints \"The old value for DUB was Dublin.\"\n\nif let airportName = airports[\"DUB\"] {\n    print(\"The name of the airport is \\(airportName).\")\n} else {\n    print(\"That airport is not in the airports dictionary.\")\n}\n// Prints \"The name of the airport is Dublin Airport.\"\n\nairports[\"APL\"] = \"Apple International\"\n// \"Apple International\" is not the real airport for APL, so delete it\nairports[\"APL\"] = nil\n// APL has now been removed from the dictionary\n\nif let removedValue = airports.removeValue(forKey: \"DUB\") {\n    print(\"The removed airport's name is \\(removedValue).\")\n} else {\n    print(\"The airports dictionary does not contain a value for DUB.\")\n}\n// Prints \"The removed airport's name is Dublin Airport.\"\n\n\n// Iterating Over a Dictionary\nfor (airportCode, airportName) in airports {\n    print(\"\\(airportCode): \\(airportName)\")\n}\n// YYZ: Toronto Pearson\n// LHR: London Heathrow\n\nfor airportCode in airports.keys {\n    print(\"Airport code: \\(airportCode)\")\n}\n// Airport code: YYZ\n// Airport code: LHR\n\nfor airportName in airports.values {\n    print(\"Airport name: \\(airportName)\")\n}\n// Airport name: Toronto Pearson\n// Airport name: London Heathrow\n\nlet airportCodes = [String](airports.keys)\n// airportCodes is [\"YYZ\", \"LHR\"]\n\nlet airportNames = [String](airports.values)\n// airportNames is [\"Toronto Pearson\", \"London Heathrow\"]\n```\n\nJavaScript\n```javascript\n// Creating an Empty Dictionary\nlet namesOfIntegers = {}\n// namesOfIntegers is an empty dictionary\nnamesOfIntegers[16] = \"sixteen\"\n// namesOfIntegers now contains 1 key-value pair\nnamesOfIntegers = {}\n// namesOfIntegers is once again an empty dictionary of type\n\n\n// Creating a Dictionary with a Dictionary Literal\nlet airports = {\"YYZ\": \"Toronto Pearson\", \"DUB\": \"Dublin\"}\n\n\n// Accessing and Modifying a Dictionary\nconsole.log(`The airports dictionary contains ${Object.keys(airports).length} items.`)\n// Prints \"The airports dictionary contains 2 items.\"\n\nif (Object.keys(airports).length == 0) {\n    console.log(\"The airports dictionary is empty.\")\n} else {\n    console.log(\"The airports dictionary is not empty.\")\n}\n// Prints \"The airports dictionary is not empty.\"\n\nairports[\"LHR\"] = \"London\"\n// the airports dictionary now contains 3 items\n\nairports[\"LHR\"] = \"London Heathrow\"\n// the value for \"LHR\" has been changed to \"London Heathrow\"\n\nconst oldValue = airports[\"DUB\"]\nairports[\"DUB\"] = \"Dublin Airport\"\nif (oldValue)  {\n    console.log(`The old value for DUB was ${oldValue}.`)\n}\n// Prints \"The old value for DUB was Dublin.\"\nconst airportName = airports[\"DUB\"]\nif (airportName) {\n    console.log(`The name of the airport is ${airportName}.`)\n} else {\n    console.log(\"That airport is not in the airports dictionary.\")\n}\n// Prints \"The name of the airport is Dublin Airport.\"\n\nairports[\"APL\"] = \"Apple International\"\n// \"Apple International\" is not the real airport for APL, so delete it\nairports[\"APL\"] = null\ndelete airports[\"APL\"]\n// APL has now been removed from the dictionary\n\n\n// Iterating Over a Dictionary\nObject.keys(airports).forEach(airportCode =\u003e {\n    const airportName = airports[airportCode]\n    console.log(`${airportCode}: ${airportName}`)\n})\n// YYZ: Toronto Pearson\n// LHR: London Heathrow\n\nlet airportCodes = Object.keys(airports)\n// airportCodes is [\"YYZ\", \"LHR\"]\n```\n\n## Control Flow\n### For-In Loops\nSwift\n```swift\nlet names = [\"Anna\", \"Alex\", \"Brian\", \"Jack\"]\nfor name in names {\n    print(\"Hello, \\(name)!\")\n}\n// Hello, Anna!\n// Hello, Alex!\n// Hello, Brian!\n// Hello, Jack!\n\nlet numberOfLegs = [\"spider\": 8, \"ant\": 6, \"cat\": 4]\nfor (animalName, legCount) in numberOfLegs {\n    print(\"\\(animalName)s have \\(legCount) legs\")\n}\n// ants have 6 legs\n// cats have 4 legs\n// spiders have 8 legs\n```\n\nJavaScript\n```javascript\nconst names = [\"Anna\", \"Alex\", \"Brian\", \"Jack\"]\nfor (let i = 0; i \u003c names.length; i++) {\n    console.log(`Hello, ${names[i]}!`)\n}\n// Hello, Anna!\n// Hello, Alex!\n// Hello, Brian!\n// Hello, Jack!\n\nconst numberOfLegs = {\"spider\": 8, \"ant\": 6, \"cat\": 4}\nObject.keys(numberOfLegs).forEach(animalName =\u003e {\n    const legCount = numberOfLegs[animalName];\n    console.log(`${animalName}s have ${legCount} legs`)\n})\n// ants have 6 legs\n// cats have 4 legs\n// spiders have 8 legs\n```\n\n### While Loops\nSwift\n```swift\nlet finalSquare = 25\nvar board = [Int](repeating: 0, count: finalSquare + 1)\nboard[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02\nboard[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08\nvar square = 0\nvar diceRoll = 0\nwhile square \u003c finalSquare {\n    // roll the dice\n    diceRoll += 1\n    if diceRoll == 7 { diceRoll = 1 }\n    // move by the rolled amount\n    square += diceRoll\n    if square \u003c board.count {\n        // if we're still on the board, move up or down for a snake or a ladder\n        square += board[square]\n    }\n}\nprint(\"Game over!\")\n```\n\nJavaScript\n```javascript\nlet finalSquare = 25\nlet board = []\nfor (let i = 0; i \u003c= finalSquare; i++) {\n    board[i] = 0;\n}\nboard[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02\nboard[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08\nlet square = 0\nlet diceRoll = 0\nwhile (square \u003c finalSquare) {\n    // roll the dice\n    diceRoll += 1\n    if (diceRoll == 7) { diceRoll = 1 }\n    // move by the rolled amount\n    square += diceRoll\n    if (square \u003c board.length) {\n        // if we're still on the board, move up or down for a snake or a ladder\n        square += board[square]\n    }\n}\nconsole.log(\"Game over!\")\n```\n### Conditional Statements\n Swift\n```swift\nvar temperatureInFahrenheit = 30\ntemperatureInFahrenheit = 90\nif temperatureInFahrenheit \u003c= 32 {\n    print(\"It's very cold. Consider wearing a scarf.\")\n} else if temperatureInFahrenheit \u003e= 86 {\n    print(\"It's really warm. Don't forget to wear sunscreen.\")\n} else {\n    print(\"It's not that cold. Wear a t-shirt.\")\n}\n// Prints \"It's really warm. Don't forget to wear sunscreen.\"\n```\n\nJavaScript\n```javascript\nlet temperatureInFahrenheit = 30\ntemperatureInFahrenheit = 90\nif (temperatureInFahrenheit \u003c= 32) {\n    console.log(\"It's very cold. Consider wearing a scarf.\")\n} else if (temperatureInFahrenheit \u003e= 86) {\n    console.log(\"It's really warm. Don't forget to wear sunscreen.\")\n} else {\n    console.log(\"It's not that cold. Wear a t-shirt.\")\n}\n// Prints \"It's really warm. Don't forget to wear sunscreen.\"\n```\n\n### Switch\nSwift\n```swift\nlet someCharacter: Character = \"z\"\nswitch someCharacter {\ncase \"a\":\n    print(\"The first letter of the alphabet\")\ncase \"z\":\n    print(\"The last letter of the alphabet\")\ndefault:\n    print(\"Some other character\")\n}\n// Prints \"The last letter of the alphabet\"\n```\n\nJavaScript\n```javascript\nconst someCharacter = \"z\"\nswitch (someCharacter) {\ncase \"a\":\n    console.log(\"The first letter of the alphabet\")\n    break;\ncase \"z\":\n    console.log(\"The last letter of the alphabet\")\n    break;\ndefault:\n    console.log(\"Some other character\")\n}\n// Prints \"The last letter of the alphabet\"\n```\n\n## Functions\nSwift\n```swift\n// Defining and Calling Functions\nfunc greet(person: String) -\u003e String {\n    let greeting = \"Hello, \" + person + \"!\"\n    return greeting\n}\nprint(greet(person: \"Anna\"))\n// Prints \"Hello, Anna!\"\nprint(greet(person: \"Brian\"))\n// Prints \"Hello, Brian!\"\n\nfunc greetAgain(person: String) -\u003e String {\n    return \"Hello again, \" + person + \"!\"\n}\nprint(greetAgain(person: \"Anna\"))\n// Prints \"Hello again, Anna!\"\n\n\n// Function Parameters and Return Values\n// Functions Without Parameters\nfunc sayHelloWorld() -\u003e String {\n    return \"hello, world\"\n}\nprint(sayHelloWorld())\n// Prints \"hello, world\"\n\n// Functions With Multiple Parameters\nfunc greet(person: String, alreadyGreeted: Bool) -\u003e String {\n    if alreadyGreeted {\n        return greetAgain(person: person)\n    } else {\n        return greet(person: person)\n    }\n}\nprint(greet(person: \"Tim\", alreadyGreeted: true))\n// Prints \"Hello again, Tim!\"\n\n\n// Functions Without Return Values\nfunc greet(person: String) {\n    print(\"Hello, \\(person)!\")\n}\ngreet(person: \"Dave\")\n// Prints \"Hello, Dave!\"\n\n// Functions with Multiple Return Values\nfunc minMax(array: [Int]) -\u003e (min: Int, max: Int) {\n    var currentMin = array[0]\n    var currentMax = array[0]\n    for value in array[1..\u003carray.count] {\n        if value \u003c currentMin {\n            currentMin = value\n        } else if value \u003e currentMax {\n            currentMax = value\n        }\n    }\n    return (currentMin, currentMax)\n}\nlet bounds = minMax(array: [8, -6, 2, 109, 3, 71])\nprint(\"min is \\(bounds.min) and max is \\(bounds.max)\")\n// Prints \"min is -6 and max is 109\"\n\n// Nested Functions\nfunc chooseStepFunction(backward: Bool) -\u003e (Int) -\u003e Int {\n    func stepForward(input: Int) -\u003e Int { return input + 1 }\n    func stepBackward(input: Int) -\u003e Int { return input - 1 }\n    return backward ? stepBackward : stepForward\n}\nvar currentValue = -4\nlet moveNearerToZero = chooseStepFunction(backward: currentValue \u003e 0)\n// moveNearerToZero now refers to the nested stepForward() function\nwhile currentValue != 0 {\n    print(\"\\(currentValue)... \")\n    currentValue = moveNearerToZero(currentValue)\n}\nprint(\"zero!\")\n// -4...\n// -3...\n// -2...\n// -1...\n// zero!\n```\n\nJavaScript\n```javascript\n// Defining and Calling Functions\nfunction greet(person) {\n    const greeting = \"Hello, \" + person + \"!\"\n    return greeting\n}\nconsole.log(greet(\"Anna\"))\n// Prints \"Hello, Anna!\"\nconsole.log(greet(\"Brian\"))\n// Prints \"Hello, Brian!\"\n\nfunction greetAgain(person) {\n    return \"Hello again, \" + person + \"!\"\n}\nprint(greetAgain(\"Anna\"))\n// Prints \"Hello again, Anna!\"\n\n\n// Function Parameters and Return Values\n// Functions Without Parameters\nfunction sayHelloWorld() {\n    return \"hello, world\"\n}\nconsole.log(sayHelloWorld())\n// Prints \"hello, world\"\n\n// Functions With Multiple Parameters\nfunction greet(person, alreadyGreeted) {\n    if (alreadyGreeted) {\n        return greetAgain(person)\n    } else {\n        return greet(person)\n    }\n}\nconsole.log(greet(\"Tim\", true))\n// Prints \"Hello again, Tim!\"\n\n\n// Functions Without Return Values\nfunction greet(person) {\n    console.log(`Hello, ${person}!`)\n}\ngreet(\"Dave\")\n// Prints \"Hello, Dave!\"\n\n// Functions with Multiple Return Values\nfunction minMax(array) {\n    let currentMin = array[0]\n    let currentMax = array[0]\n    array.forEach(value =\u003e {\n        if (value \u003c currentMin) {\n            currentMin = value\n        } else if (value \u003e currentMax) {\n            currentMax = value\n        }\n    })\n    return {currentMin, currentMax}\n}\nconst bounds = minMax([8, -6, 2, 109, 3, 71])\nconsole.log(`min is ${bounds.min} and max is ${bounds.max}`)\n// Prints \"min is -6 and max is 109\"\n\n// Nested Functions\nfunction chooseStepFunction(backward) {\n    function stepForward(input) { return input + 1 }\n    function stepBackward(input) { return input - 1 }\n    return backward ? stepBackward : stepForward\n}\nlet currentValue = -4\nconst moveNearerToZero = chooseStepFunction(currentValue \u003e 0)\n// moveNearerToZero now refers to the nested stepForward() function\nwhile (currentValue != 0) {\n    console.log(`${currentValue}... `)\n    currentValue = moveNearerToZero(currentValue)\n}\nconsole.log(\"zero!\")\n// -4...\n// -3...\n// -2...\n// -1...\n// zero!\n```\n## Closures\nSwift\n```swift\n// Closure Expressions\n// The Sorted Method\nlet names = [\"Chris\", \"Alex\", \"Ewa\", \"Barry\", \"Daniella\"]\nfunc backward(_ s1: String, _ s2: String) -\u003e Bool {\n    return s1 \u003e s2\n}\nvar reversedNames = names.sorted(by: backward)\n// reversedNames is equal to [\"Ewa\", \"Daniella\", \"Chris\", \"Barry\", \"Alex\"]\nreversedNames = names.sorted(by: { (s1: String, s2: String) -\u003e Bool in\n    return s1 \u003e s2\n})\n// or\nreversedNames = names.sorted(by: { (s1: String, s2: String) -\u003e Bool in return s1 \u003e s2 } )\n```\n\nJavaScript\n```javascript\n// Closure Expressions\n// The Sort Method\nconst names = [\"Chris\", \"Alex\", \"Ewa\", \"Barry\", \"Daniella\"]\nfunction backward(s1, s2) {\n    return s1 \u003c s2\n}\nlet reversedNames = names.sort(backward)\n// reversedNames is equal to [\"Ewa\", \"Daniella\", \"Chris\", \"Barry\", \"Alex\"]\nreversedNames = names.sort((s1, s2) =\u003e {\n    return s1 \u003c s2\n})\n// or\nreversedNames = names.sort((s1, s2) =\u003e return s1 \u003c s2)\n```\n## Classes\nSwift\n```swift\n// class definition\nclass Counter {\n    var count = 0\n    func increment() {\n        count += 1\n    }\n    func increment(by amount: Int) {\n        count += amount\n    }\n    func reset() {\n        count = 0\n    }\n}\n\n// class instance\nlet counter = Counter()\n// the initial count value is 0\ncounter.increment()\n// the count's value is now 1\ncounter.increment(by: 5)\n// the count's value is now 6\ncounter.reset()\n// the count's value is now 0\n\nprint(\"The count property value is \\(counter.count)\")\n\n```\n\nJavaScript\n```javascript\n// class definition\nclass Counter {\n    contructor() {\n        this.count = 0\n    }\n    function increment() {\n        this.count += 1\n    }\n    function increment(amount) {\n        this.count += amount\n    }\n    function reset() {\n        this.count = 0\n    }\n}\n\n// class instance\nlet counter = Counter()\n// the initial count value is 0\ncounter.increment()\n// the count's value is now 1\ncounter.increment(5)\n// the count's value is now 6\ncounter.reset()\n// the count's value is now 0\n\nconsole.log(`The count property value is ${counter.count}`)\n```\n\n## Inheritance\nSwift\n```swift\n// Defining a Base Class\nclass Vehicle {\n    var currentSpeed = 0.0\n    var description: String {\n        return \"traveling at \\(currentSpeed) miles per hour\"\n    }\n    func makeNoise() {\n        // do nothing - an arbitrary vehicle doesn't necessarily make a noise\n    }\n}\nlet someVehicle = Vehicle()\nprint(\"Vehicle: \\(someVehicle.description)\")\n// Vehicle: traveling at 0.0 miles per hour\n\n\n// Subclassing\nclass SomeSubclass: SomeSuperclass {\n    // subclass definition goes here\n}\nclass Bicycle: Vehicle {\n    var hasBasket = false\n}\nlet bicycle = Bicycle()\nbicycle.hasBasket = true\n\nbicycle.currentSpeed = 15.0\nprint(\"Bicycle: \\(bicycle.description)\")\n// Bicycle: traveling at 15.0 miles per hour\n\n\n// Subclasses can themselves be subclassed\nclass Tandem: Bicycle {\n    var currentNumberOfPassengers = 0\n}\nlet tandem = Tandem()\ntandem.hasBasket = true\ntandem.currentNumberOfPassengers = 2\ntandem.currentSpeed = 22.0\nprint(\"Tandem: \\(tandem.description)\")\n// Tandem: traveling at 22.0 miles per hour\n\n\n// Overriding\nclass Train: Vehicle {\n    override func makeNoise() {\n        print(\"Choo Choo\")\n    }\n}\nlet train = Train()\ntrain.makeNoise()\n// Prints \"Choo Choo\"\n\n\n// Overriding Property Getters and Setters\nclass Car: Vehicle {\n    var gear = 1\n    override var description: String {\n        return super.description + \" in gear \\(gear)\"\n    }\n}\nlet car = Car()\ncar.currentSpeed = 25.0\ncar.gear = 3\nprint(\"Car: \\(car.description)\")\n// Car: traveling at 25.0 miles per hour in gear 3\n```\n\nJavaScript\n```javascript\n// Defining a Base Class\nclass Vehicle {\n    constructor() {\n        this.currentSpeed = 0.0\n    }\n    get description() {\n        return `traveling at ${currentSpeed} miles per hour`\n    }\n    function makeNoise() {\n        // do nothing - an arbitrary vehicle doesn't necessarily make a noise\n    }\n}\nlet someVehicle = Vehicle()\nconsole.log(`Vehicle: ${someVehicle.description}`)\n// Vehicle: traveling at 0.0 miles per hour\n\n\n// Subclassing\nclass SomeSubclass extends SomeSuperclass {\n    contructor() {\n        super();\n    }\n    // subclass definition goes here\n}\nclass Bicycle extends Vehicle {\n    contructor() {\n        super();\n        this.hasBasket = false\n    }\n}\nlet bicycle = Bicycle()\nbicycle.hasBasket = true\n\nbicycle.currentSpeed = 15.0\nconsole.log(`Bicycle: ${bicycle.description}`)\n// Bicycle: traveling at 15.0 miles per hour\n\n\n// Subclasses can themselves be subclassed\nclass Tandem extends Bicycle {\n    contructor() {\n        super();\n        this.currentNumberOfPassengers = 0\n    }\n}\nlet tandem = Tandem()\ntandem.hasBasket = true\ntandem.currentNumberOfPassengers = 2\ntandem.currentSpeed = 22.0\nconsole.log(\"Tandem: \\(tandem.description)\")\n// Tandem: traveling at 22.0 miles per hour\n\n\n// Overriding\nclass Train extends Vehicle {\n    contructor() {\n        super();\n        this.currentNumberOfPassengers = 0\n    }\n    function makeNoise() {\n        console.log(\"Choo Choo\")\n    }\n}\nlet train = Train()\ntrain.makeNoise()\n// Prints \"Choo Choo\"\n\n\n// Overriding Property Getters and Setters\nclass Car extends Vehicle {\n    contructor() {\n        super();\n        this.gear = 1\n    }\n    get description() {\n        return `${super.description} in gear ${gear}`\n    }\n}\nlet car = Car()\ncar.currentSpeed = 25.0\ncar.gear = 3\nconsole.log(`Car: ${car.description}`)\n// Car: traveling at 25.0 miles per hour in gear 3\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funbug%2Fsj","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Funbug%2Fsj","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funbug%2Fsj/lists"}