{"id":20260351,"url":"https://github.com/haraldbregu/swift_hidden_features","last_synced_at":"2026-05-13T02:10:19.720Z","repository":{"id":188406643,"uuid":"605937234","full_name":"HaraldBregu/Swift_Hidden_Features","owner":"HaraldBregu","description":"A short and intuitive documentation about swift basics \u0026 hidden features","archived":false,"fork":false,"pushed_at":"2023-03-01T11:08:55.000Z","size":171,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-14T04:14:14.068Z","etag":null,"topics":["ios","swift5","xcode"],"latest_commit_sha":null,"homepage":"https://megageneral.com","language":"Swift","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/HaraldBregu.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,"governance":null}},"created_at":"2023-02-24T08:20:27.000Z","updated_at":"2023-02-28T08:16:10.000Z","dependencies_parsed_at":"2023-08-15T07:10:46.507Z","dependency_job_id":"fc259df5-2fd7-43e1-88cc-a57607f04c9e","html_url":"https://github.com/HaraldBregu/Swift_Hidden_Features","commit_stats":null,"previous_names":["haraldbregu/swift_hidden_features"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HaraldBregu%2FSwift_Hidden_Features","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HaraldBregu%2FSwift_Hidden_Features/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HaraldBregu%2FSwift_Hidden_Features/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HaraldBregu%2FSwift_Hidden_Features/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HaraldBregu","download_url":"https://codeload.github.com/HaraldBregu/Swift_Hidden_Features/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241720424,"owners_count":20008975,"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":["ios","swift5","xcode"],"created_at":"2024-11-14T11:19:16.503Z","updated_at":"2026-05-13T02:10:19.714Z","avatar_url":"https://github.com/HaraldBregu.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Swift Basic \u0026 Hidden Features\n=====================================================\n\nHello and Welcome! \n\nAs one of the most popular programming languages today, Swift is widely used by developers across the globe to create everything from mobile apps to server-side applications. But did you know that Swift also has a range of hidden or lesser-known features that can help you write more efficient, streamlined, and expressive code? In this post, we'll explore some of these hidden gems of the Swift programming language and show you how to use them to your advantage.\n\n\nSwift Basics\n------------\n\n[Playground Example](https://github.com/HaraldBregu/Swift_Hidden_Features/tree/main/swift_basics.playground)\n\nUsing semicolon when writing multiple statement in the same line.\n\n```swift\n\nlet hello = \"Hello\"; print(hello); let world = \"World\"; print(world)\n```\n\nWhen working with integers swift gives the possibility to get the min and the max of each type of integer.\n\n```swift\nprint(UInt8.min) // 0\nprint(UInt8.max) // 255\nprint(Int8.min) // -128\nprint(Int8.max) // 127\nprint(Int.min) // minus value\nprint(Int.max) // maximum value\nprint(UInt32.max) // 4294967295\n```\n\nTouples are a way to group multiple values\nto a single compound value.\n\n```swift\nlet toupleYear = (2034, \"Future year\")\nprint(toupleYear.0) // Printing first parameter\nprint(toupleYear.1) // Printing second parameter\n\nlet (param0, param1) = toupleYear\nprint(param0) // Printing first parameter\nprint(param1) // Printing second parameter\n```\n\nOptionals with shorter spelling to unwrap optional value\n\n```swift\nlet optionalName: String? = nil\nif let optionalName {\n    print(\"My name is \\(optionalName)\")\n}\n```\n\nError handling\n\n```swift\nenum InfoErrors: Error {\n    case wrongName\n    case wrongVat\n    case wrongAge\n}\n\nfunc insertMyName() throws -\u003e Bool {\n    throw InfoErrors.wrongName\n}\n\ndo {\n    try insertMyName()\n} catch InfoErrors.wrongName {\n    // an error was thrown\n} catch InfoErrors.wrongVat {\n    // an error was thrown\n} catch InfoErrors.wrongAge {\n    // an error was thrown\n}\n```\nAssertions \u0026 Preconditions\nAssertions are checked only in debug builds, but preconditions are checked in both debug and production builds.\n\n```swift\nlet name = \"stupid\"\nassert(name != \"stupid\", \"A person's name can't be unapropriate.\")\n\nlet age = 18\nprecondition(age \u003e 17, \"Person must be adult.\")\n```\nString and Characters\n\n```swift\n// String written in multiline\nlet multilineString = \"\"\"\nThese are the same.\n\"\"\"\n\n// With wrapped quotation\nlet softWrappedQuotation = \"\"\"\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\nlet lineBreaks = \"\"\"\n\nThis string starts with a line break.\nIt also ends with a line break.\n\n\"\"\"\n// Three double quotation marks\nlet threeDoubleQuotationMarks = \"\"\"\nEscaping all three quotation marks \\\"\\\"\\\"\n\"\"\"\n\n// Three more double quotation marks\nlet threeMoreDoubleQuotationMarks = #\"\"\"\nHere are three more double quotes: \"\"\"\n\"\"\"#\n```\n\nIndices\n\n```swift\nlet greeting = \"Guten Tag!\"\ngreeting[greeting.startIndex]\ngreeting[greeting.index(before: greeting.endIndex)] // G\ngreeting[greeting.index(after: greeting.startIndex)] // !\nlet index = greeting.index(greeting.startIndex, offsetBy: 7) // u\ngreeting[index]\n```\n\nInserting and Removing\n\n```swift\nvar welcome = \"hello world\"\nwelcome.insert(\"!\", at: welcome.endIndex) // welcome now equals \"hello world!\"\nwelcome.insert(contentsOf: \" whats'up\", at: welcome.index(before: welcome.endIndex)) // hello world whats'up!\nwelcome.remove(at: welcome.index(before: welcome.endIndex))\nwelcome\nlet range = welcome.index(welcome.endIndex, offsetBy: -15)..\u003cwelcome.endIndex\nwelcome.removeSubrange(range)\nwelcome\n```\nSubstrings\n\n```swift\n// Substrings\nlet myNameAndProfession = \"Harald Bregu, iOS Developer\"\nlet index = myNameAndProfession.firstIndex(of: \",\") ?? greeting.endIndex\nlet myNameOnly = myNameAndProfession[..\u003cindex]\nmyNameOnly // Harald Bregu\nlet newString = String(myNameOnly)\nnewString\n```\n\n### Colletion types\n\n[Playground Example](https://github.com/HaraldBregu/Swift_Hidden_Features/tree/main/collection_types.playground)\n\nArrays\n\n```swift\n// Inserting data to an array in 3 ways\nvar simpleArray = [\"Earth\", \"Moon\"]\nsimpleArray.append(\"Mars\")\nsimpleArray += [\"Mercury\"]\nsimpleArray += [\"Venus\", \"Pluto\"]\n\n// Replacing items into array in 2 ways\nsimpleArray[0] = \"Jupiter\"\nsimpleArray[4...5] = [\"Earth\", \"Saturn\"]\n```\n\nSet collection type\n\n```swift\n// Remove duplicated items in an array with Set\nvar arrayWithDouplicatedItems = [\"Apple\", \"Banana\", \"Kiwi\", \"Apple\", nil]\nvar rem = Set(arrayWithDouplicatedItems)\n```\n\n### Hidden Feature \n\n[Playground Example](https://github.com/HaraldBregu/Swift_Hidden_Features/tree/main/hidden_features.playground)\n\nFallthrough\n\n```swift\nlet skill = \"programmer\"\nvar description = \"My skills are: \\(skill), \"\n\nswitch skill {\ncase \"programmer\", \"datas cientist\":\n    description += \"developer, \"\n    description += \"data scientist\"\n    fallthrough\ndefault:\n    description += \" and also a computer entusiast\"\n}\nprint(description)\n// Prints \"My skills are: programmer, developer, data scientist and also a computer entusiast\\\"\n```\n\nFunctions with touple\n\n```swift\nfunc firstAndLastLetterOfMyName(string: String) -\u003e (first: String, last: String)  {\n    return (String(string.prefix(1)), String(string.suffix(1)))\n}\n\nfirstAndLastLetterOfMyName(string: \"Harald\").first\nfirstAndLastLetterOfMyName(string: \"Harald\").last\n```\n\nIn-Out Parameters\n\n```swift\nfunc swapTwoWords(_ a: inout String, _ b: inout String) {\n    let temporaryA = a\n    a = b\n    b = temporaryA\n}\n\nvar myName = \"Bregu\"\nvar mySurName = \"Harald\"\nprint(\"My full name is: \\(myName) \\(mySurName)\")\nswapTwoWords(\u0026myName, \u0026mySurName)\nprint(\"My full name is: \\(myName) \\(mySurName)\")\n\n```\n\nClosures\n\n```swift\n//There are 3 ways to use a closure\nfunc sendCommand(callbackClosure: () -\u003e Void) {\n\n    // After sending command call closure\n    callbackClosure()\n}\n\nsendCommand() {}\n\nsendCommand {}\n\nsendCommand(callbackClosure: {})\n```\n\nEnums\n\n```swift\n// Iterable and raw value\nenum Nations: String, CaseIterable {\n    case italy = \"IT\", germany = \"DE\", france = \"FR\"\n}\n\n// Get the count of the cases\nprint(\"\\(Nations.allCases.count) nations\")\n\n// Print Raw Value\nprint(Nations.italy.rawValue)\n\n// Get type by raw value\nlet possibleNation = Nations(rawValue: \"IT\")\nif let possibleNation {\n    \n    print(possibleNation)\n}\n\n// Recursive enumeration\nindirect enum StarSystem {\n    case planets(Int)\n    case star(Int)\n    case satelites(Int)\n    case add(StarSystem, StarSystem)\n}\n\nlet numStars = StarSystem.star(2)\nlet numNearPlanets = StarSystem.planets(5)\nlet numSatelites = StarSystem.satelites(24)\nlet product = StarSystem.add(numStars, StarSystem.add(numNearPlanets, numSatelites))\n\nswitch product {\ncase .add(let first, let second):\n    print(first)\n    print(second)\n    break\ncase .planets(_): break\ncase .star(_): break\ncase .satelites(_): break\n}\n```\n\n### Structures and Classes\n\n| Features                          | Struct | Classes |\n| :-------------------------------- |:------:| :-----: |\n|   Define properties to store values | \u0026check;   |  \u0026check;   |\n|   Define methods to provide functionality | \u0026check;   |  \u0026check;   |\n|   Define subscripts to provide access to their values using subscript syntax  | \u0026check;   |  \u0026check;   |\n|   Define initializers to set up their initial state   | \u0026check;   |  \u0026check;   |\n|   Be extended to expand their functionality beyond a default implementation   | \u0026check;   |  \u0026check;   |\n|   Conform to protocols to provide standard functionality of a certain kind    | \u0026check;   |  \u0026check;   |\n|   Inheritance enables one class to inherit the characteristics of another |\u0026cross;|\u0026check;|\n|   Type casting enables you to check and interpret the type of a class instance at runtime |\u0026cross;|\u0026check;|\n|   Deinitializers enable an instance of a class to free up any resources it has assigned   |\u0026cross;|\u0026check;|\n|   Reference counting allows more than one reference to a class instance  |\u0026cross;|\u0026check;|\n \n ### Properties\n \n There are 5 type of properties\n \n * Stored Properties\n * Lazy Stored Properties\n * Computed Properties\n * Read-Only Computed Properties\n * Property Observers\n * Property Wrappers\n \n Property Wrappers\n\n```swift\n@propertyWrapper\nstruct SpeedLimit {\n    private var number: Int\n    private var maximum: Int\n    private(set) var projectedValue: String\n    var wrappedValue: Int {\n        get { return number }\n        set {\n            if newValue \u003c 50 \u0026\u0026 newValue \u003e= 20 {\n                number = newValue\n                projectedValue = \"Is on urban limits speed\"\n            } else if newValue \u003c 20 {\n                projectedValue = \"Is very slow\"\n                number = newValue\n            }  else if newValue \u003e maximum {\n                projectedValue = \"Is faster than max limit\"\n                number = min(newValue, maximum)\n            } else {\n                projectedValue = \"Is very fast\"\n                number = newValue\n            }\n        }\n    }\n    \n    init() {\n        projectedValue = \"Is off\"\n        number = 40\n        maximum = 300\n    }\n}\n\nstruct Car {\n    @SpeedLimit var speed: Int\n}\n\nvar myBMWCar = Car()\nprint(myBMWCar.$speed) // Prints \"is off\"\n \nmyBMWCar.speed = 40\nprint(myBMWCar.speed) // Prints \"40\"\nprint(myBMWCar.$speed) // Prints \"Is on urban limits speed\"\n\nmyBMWCar.speed = 100\nprint(myBMWCar.speed) // Prints \"100\"\nprint(myBMWCar.$speed) // Prints \"is very fast\"\n\nmyBMWCar.speed = 454\nprint(myBMWCar.speed) // Prints \"300\"\nprint(myBMWCar.$speed) // Prints \"Is faster than max limit\"\n```\n\nSubscript Syntax\n\n```swift\nstruct CarPower {\n    let powerkw: Double\n    subscript(index: Double) -\u003e Double {\n        return powerkw * index\n    }\n}\nlet carPower = CarPower(powerkw: 80)\nprint(\"CarPower in horsepower is: \\(carPower[1.35962])\")\n\nenum Planet: Int {\n    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune\n    static subscript(n: Int) -\u003e Planet {\n        return Planet(rawValue: n)!\n    }\n}\n\nprint(Planet[4])\n```\n\nConcurrency\n\n```swift\nimport UIKit\nimport PlaygroundSupport\nimport _Concurrency\n\nPlaygroundPage.current.needsIndefiniteExecution = true\n\nfunc showSomeResults() async -\u003e [Int] {\n    (0..\u003c99).map { _ in .random(in: 1...20) }\n}\n\nvar result = await showSomeResults()\n\nprint(result)\nPlaygroundPage.current.finishExecution()\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fharaldbregu%2Fswift_hidden_features","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fharaldbregu%2Fswift_hidden_features","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fharaldbregu%2Fswift_hidden_features/lists"}