{"id":9015,"date":"2022-01-04T21:11:55","date_gmt":"2022-01-04T21:11:55","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=9015"},"modified":"2022-02-28T21:43:42","modified_gmt":"2022-02-28T21:43:42","slug":"swift-basics-lets-try-this-again","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/swift-basics-lets-try-this-again\/","title":{"rendered":"Swift basics &#8211; let&#8217;s try this again"},"content":{"rendered":"<p>A while back I looked into the Swift programming language but had so many other things on at the time that I didn&#8217;t get far with it, so let&#8217;s try again but from the basics. <\/p>\n<p>This post is the equivalent of a <em>cheat sheet<\/em> of the basics of Swift. <\/p>\n<p><em>Note: ofcourse there&#8217;s no way I could include everything about a language in a single post, so this in non-exhaustive and primarily aimed at understanding key points of the language to get us up and running quickly.<\/em><\/p>\n<p><strong>What are the absolute basics I need to know about Swift?<\/strong><\/p>\n<ul>\n<li>Swift does not require semi-colons at the end of lines unless a single line has multiple statements<\/li>\n<li>We declare variables using the <em>var<\/em> keyword and const values use <em>let<\/em> and we can either supply type annotation if we want to be explicit about the type used (which we need to do if declaring a float as double is implicitly used if decimal point numbers are used), for example\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar a: Int = 1  \/\/ variable, explicit type\r\nvar b = 1       \/\/ variable, implicit type\r\nlet s = &quot;Hello&quot; \/\/ constant, implicit type\r\nlet dbl = 42.9  \/\/ constant double, implicit type\r\nlet fl: Float = 42.9  \/\/ constant float, requires explicit type\r\n<\/pre>\n<p>Interestingly constants in Swift (using the <em>let<\/em> keyword) are evaluated at runtime, unlike some other languages, hence they can be assigned at runtime.\n<\/li>\n<li>Nulls exist within Swift, but they&#8217;re known as <em>nil<\/em><\/li>\n<li>Like other languages, We can declare numbers as hexadecimal , binary etc. For example\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet million = 1_000_000\r\nlet binary = 0b1010\r\nlet oct = 0o52\r\nlet hex = 0x2a\r\n<\/pre>\n<\/li>\n<li>We can also declare variables using the types initialization methods, for example\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet a = Double(42)\r\nlet b = Int(1.2)\r\nlet c = Int(&quot;123&quot;)\r\n<\/pre>\n<p>In the above <em>b<\/em> is equivalent to <em>Int(round(1.2))<\/em> and <em>c<\/em> attempts to convert the string to an Int.\n<\/li>\n<li>Type aliasing can be used to declare an alias to a type, which is useful for more complex types or just to give a type some context to it&#8217;s usage, for example\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\ntypealias counter = Int\r\ntypealias Predicate = (s: String) -&gt; Bool\r\n<\/pre>\n<\/li>\n<li>Int, Bool, Double and other such types are value types, meaning they&#8217;re passed by value, however unlike some other languages, String, Array and Dictionary are also passed by value. Swift uses copy on write (COW) to ensure that when we pass around an array (for example) it&#8217;s actually a copy of the reference until the time that it&#8217;s mutated, then a copy is made.\n<\/li>\n<li>The usual operators, -,+,\/,*,% as well as += etc. exist but there is no ++ or &#8212; in the latest version of Swift. Hence we instead use += 1 and -= 1 in it&#8217;s place<\/li>\n<li>The standard ==, !=, <, >, <=, >= comparison operators exist as do the logical operators || and &#038;&#038;<\/li>\n<li>Ternary operators (as per C++\/C# etc.) exists so we can write\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet a = b &gt; 0 ? &quot;+ve&quot; : &quot;-ve or zero&quot;\r\n<\/pre>\n<\/li>\n<li>Parenthesis are not used around control flow i.e.\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nif a &gt; 0 {\r\n}\r\n<\/pre>\n<\/ul>\n<p><strong>Value and Reference Types<\/strong><\/p>\n<p>As mentioned above, many types are value types in Swift, these include structures, enumerations and tuples as well as the basic types, Int, Bool etc. which is probably expected, however Array, Dictionary and Set are also value types which might not be expected.<\/p>\n<p>Classes are reference types, and just like many other languages &#8211; the big difference between value and reference types is how they&#8217;re passed between functions.<\/p>\n<p>Value types are passed by passing a copy of the instance (in other words any changes made are not reflected in the calling code reference). Reference types are passed by reference and hence changes to the instance are reflected in the original instance.<\/p>\n<p>Swift uses COW (copy on write) for assignment of value type instances, however not all value types get this.<\/p>\n<p><strong>Conventions<\/strong><\/p>\n<p>I always believe that when you write code in different languages you should try to write in the conventions and idioms of that languages. <\/p>\n<ul>\n<li>Classes, structs etc. should use PascalCase (also known as CapitalizedCamelCase)<\/li>\n<li>Variables, constants, function\/method names should use camelCase (also known as uncapitalizedCamelCase)<\/li>\n<li>The preference is for curly braces not be on a line of their own except the last brace, in other words\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nif a &gt; 0 {\r\n} else {\r\n}\r\n\r\n\/\/ is preferred over\r\n\r\nif a &gt; 0\r\n{\r\n}\r\nelse\r\n{\r\n}\r\n<\/pre>\n<\/li>\n<li>Instead of naming functions like this <em>addItem<\/em> a preference seems to be, where appropriate, to instead use a more generic name which the parameter name giving more information, i.e. <em>add(item: String)<\/em> &#8211; we&#8217;ll look at functions soon.<\/li>\n<\/ul>\n<p><strong>Comments<\/strong><\/p>\n<p>Single line comments start with \/\/ and block comments \/* *\/, one difference to some other languages is we can also nest block comments, for example \/* \/* *\/ *\/<\/p>\n<p><strong>nil and Optionals<\/strong><\/p>\n<p>As mentioned earlier <em>nil<\/em> is the Swift equivalent of NULL, null etc. Swift has optionals (or nullables) which also extend to the String type, hence the syntax <em>String?<\/em> means String is optional\/nullable and we therefor also have syntax such as the following to ensure <em>person<\/em> is not nil<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet fn = person?.firstName\r\n<\/pre>\n<p>To unwrap an optional we use !, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nif person.firstName != nil {\r\n  let fn = person.firstName! \r\n}\r\n<\/pre>\n<p>Swift also include the nil coalescing operator f<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet a = b ?? c\r\n<\/pre>\n<p><strong>Arrays<\/strong><\/p>\n<p>Arrays are declared using fairly standard [] syntax, i.e.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet a = &#x5B;21, 22, 23] \r\nlet c = a + &#x5B;45, 46] \/\/ concat the two arrays\r\n<\/pre>\n<p><strong>Dictionary<\/strong><\/p>\n<p>Dictionaries can be declare using a key\/value array syntax, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet d = &#x5B;&quot;A&quot;: &quot;1&quot;, &quot;B&quot;, &quot;2&quot;]\r\nlet empty = &#x5B;:] \/\/ empty dictionary\r\n<\/pre>\n<p><strong>Set<\/strong><\/p>\n<p>Sets are simply unordered arrays in essence so can be declared using the same syntax but we need to supply an explicit type to Swift, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet s: Set = &#x5B;1, 2]\r\n<\/pre>\n<p><strong>Strings<\/strong><\/p>\n<p>A string is a struct, hence passed by value and uses standard string syntax as per this example <em>&#8220;Hello&#8221;<\/em> but also a character is a single string value, i.e. <em>&#8220;a&#8221;<\/em>.<\/p>\n<p>String interpolation uses the \\(&#8230;) syntax, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet s = &quot;\\(count) items&quot;\r\n<\/pre>\n<p><strong>Tuples<\/strong><\/p>\n<p>Most languages seem to include a Tuple type, Swift is no different, we declare a tuple like this <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet t1 = (1, &quot;One&quot;)\r\n<\/pre>\n<p>and as we&#8217;re not using named parameters, access to the values in the tuple are accessed via<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet n = t1.0\r\nlet s = t1.1\r\n<\/pre>\n<p>Alternatively we can declare the tuple with named params, i.e.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet t1 = (idx: 1, name: &quot;One&quot;)\r\n<\/pre>\n<p>Now we can access via the names, i.e.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet n = t1.idx\r\nlet s = t1.name\r\n<\/pre>\n<p><strong>Switch statements<\/strong><\/p>\n<p>Switch statement are very similar to C# etc. except they do not (be default) fall-through to the next case statement, hence <em>break<\/em> is only needed where we need to exit a case block before the end. The <em>default<\/em> case is also not a requirement like it is for exhaustive switch statements.<\/p>\n<p>Let&#8217;s look at some examples<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nswitch color {\r\n  case &quot;red&quot;:\r\n    print(&quot;it's red&quot;)  \r\n  default:\r\n    print(&quot;not red&quot;)\r\n}\r\n<\/pre>\n<p>We can also use compound cases, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nswitch color {\r\n  case &quot;red&quot;, &quot;white&quot;, &quot;blue&quot;: \r\n    print(&quot;it's red, white or blue&quot;)  \r\n  default:\r\n    print(&quot;not red, white or blue&quot;)\r\n}\r\n<\/pre>\n<p>For integers we can also use ranges do switch on, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\ncase 0...&lt;10:\r\n  print(&quot;less than ten&quot;)\r\ncase 10...20:\r\n  print(&quot;between 10 and 20&quot;)\r\n<\/pre>\n<p>We can extend this further using the <em>where<\/em> keyword, for example if a value is within a range of values and where it also matches another predicate<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nswitch a {\r\n  case 0...10 where a % 2 == 0\r\n    print(&quot;Event num between 0 and 10&quot;)\r\n}\r\n\r\nTuple matching exists where we can match all parameters or some, using a discard to ignore a parameter, for example\r\n\r\n&#x5B;code language=&quot;csharp&quot;]\r\nlet t = (0, 2)\r\nswitch t {\r\n  case (0, 0):\r\n    \/\/ do something\r\n  case (0, _):\r\n    \/\/ only care about first item\r\n  case (_, 0):\r\n    \/\/ only care about second item\r\n}\r\n<\/pre>\n<p>Next up, we can value bind a tuple within the case clause, basically meaning we have a way to get the actual value and assign it as part of the matching process, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet t = (0, 2)\r\nswitch t {\r\n  case (0, 0):\r\n    \/\/ do something\r\n  case (let x, _):\r\n    \/\/ get's the first item assigns as x\r\n}\r\n<\/pre>\n<p>So in the above we actual switch on a (0, 0) tuple pattern but then for any other we just assign the first parameter to <em>x<\/em> and discard the second.<\/p>\n<p>I mentioned that <em>break<\/em> is used in some case, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nswitch a {\r\n  case (let a) where a % 2 == 0\r\n    if(a == 4) {\r\n      break\r\n    }\r\n\r\n    print(&quot;Even number between 0 and 10 but not 4&quot;)\r\n}\r\n<\/pre>\n<p>On the other hand, if we actually do want our cases to fall-through then we can use the <em>fallthrough<\/em> keyword, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nswitch a {\r\n  case (let a) where a % 2 == 0\r\n    print(&quot;Is even&quot;)\r\n    fallthrough\r\n  case 4\r\n    print(&quot;Is 4&quot;)\r\n}\r\n<\/pre>\n<p><strong>Loops<\/strong><\/p>\n<p>We&#8217;ve seen earlier that ++ and &#8212; do not exist in Swift, so the C#\/Java\/C++ way of looping is not going to exist, instead Swift generally uses a syntax more in line with enumerables using ranges (denoted by <em>start<\/em>&#8230;<em>end<\/em> to denote the start and end of a loop)<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfor i in 1...10 {\r\n  print(i)\r\n}\r\n<\/pre>\n<p>So this works rather like C# <em>foreach<\/em>, hence as you&#8217;d expect, we can iterate over array items and dictionaries using pretty much the same syntax, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet a = &#x5B;1,10,200]\r\n\r\nfor i in a {\r\n  \/\/ do something with i\r\n}\r\n<\/pre>\n<p>With dictionaries we simply deconstruct the tuples of key\/value like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfor (a, b) in dictionary {\r\n  \/\/ do something with a and\/or b\r\n}\r\n<\/pre>\n<p>While loops also exist, and in these we will need to use the += or -= , for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nwhile i &lt; 10 {\r\n  i += 1\r\n}\r\n\r\nrepeat {\r\n  i += 1\r\n} while i &lt; 10\r\n<\/pre>\n<p><strong>Functions<\/strong><\/p>\n<p>Functions are written in the form<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc funtionName(arg: argType) -&gt; returnType {   \r\n}\r\n<\/pre>\n<p>So this means we&#8217;d write an <em>add<\/em> function like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc add(a: Int, b: Int) -&gt; Int {\r\n  return a + b\r\n}\r\n<\/pre>\n<p>Calling our <em>add<\/em> function requires that we supply the names of the parameters, so to call this function we&#8217;d use the following<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nadd(a: 1, b: 2)\r\n<\/pre>\n<p>In some cases we&#8217;d prefer to have anonymous arguments, i.e. not requiring the developer to supply the names, this would require the named parameter to be prefixed by a discard, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc add(_ a: Int, _ b: Int) -&gt; Int {\r\n  return a + b\r\n}\r\n<\/pre>\n<p>and now we can just supply the arguments by index, i.e. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nadd(1, 2)\r\n<\/pre>\n<p>Interestingly we can also declare function parameters with two names, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc data(for request: URLRequest) -&gt; Srring {\r\n   \/\/ do something\r\n}\r\n<\/pre>\n<p>In this case the first name <em>for<\/em> is the external name, i.e. the caller uses, whereas the second name <em>request<\/em> is the name used internally within the actual function. <\/p>\n<p>Default values for parameters are also supported, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunction fn(s: String = &quot;Hello&quot;) -&gt; Void {\r\n}\r\n<\/pre>\n<p>Variadic arguments can be used, only one parameter can be variadic however, unlike some languages where this must be the last parameter of a function, due to variable names being used, the variadic argument can be in any position, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc addThenMultiply(values: Int..., multiplier: Int) -&gt; Int\r\n{\r\n  for v in values {\r\n     \/\/ do something\r\n  }\r\n\r\n  return somevalue\r\n}\r\n<\/pre>\n<p>and we can call this using the following<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\naddThenMultiply(args: 1, 2, 10, multiplier: 9)\r\n<\/pre>\n<p>Many of the other standard syntax exists, such as function overloading, passing functions (which are first class objects in Swift) as arguments etc.<\/p>\n<p>One interesting addition is the requirement to mark functions which change state as <em>mutating<\/em>, for example, assuming the following code was part of a Container class which changes the internal storage when we add items<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nmutating func add(item: MyClass) -&gt; Void {\r\n}\r\n<\/pre>\n<p><strong>Guards<\/strong><\/p>\n<p>The <em>guard<\/em> keyword can be used for preconditions on a functions, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc doSomething(i: Int) -&gt; Void {\r\n  guard i &gt;= 0 else {\r\n    return \r\n  }\r\n\r\n  print(&quot;Positive&quot;)\r\n}\r\n<\/pre>\n<p><strong>Closures<\/strong><\/p>\n<p>Swift supports closures and we can assign closures to variables like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar c = { print(&quot;Inside Closure&quot;) }  \/\/ () -&gt; Void\r\nvar d = { return 123 } \/\/ () -&gt; Int\r\n<\/pre>\n<p>Swift comes with a special syntax for <em>trailing closures<\/em> whereby a function is passed into another function without the need to supply the parenthesis, for example if we have a function like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc fn(f: () -&gt; Int) -&gt; Void {\r\n}\r\n<\/pre>\n<p>We can ofcourse supply one of our previously defined closures like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfn(f: d)\r\n<\/pre>\n<p>but we can also supply the closures as a trailing closure like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfn {\r\n  return 987\r\n}\r\n<\/pre>\n<p>There&#8217;s an alternative syntax that allows us to access closure parameters using the parameter index, so for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet op = (Int, Int)  -&gt; Int = { return $0 + $1 }\r\n\/\/ or shorthand version\r\nlet op = (Int, Int)  -&gt; Int = { $0 + $1 }\r\n<\/pre>\n<p><strong>Properties<\/strong><\/p>\n<p>We can declare properties on our types like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nprotocol SomeType {\r\n  var error: String { get set } \/\/ read\/write\r\n  var instance: String { get }  \/\/ readonly\r\n}\r\n<\/pre>\n<p><strong>Operator overloading<\/strong><\/p>\n<p>Operator overloading is supported, here&#8217;s an example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nextention Math {\r\n  static func +(lhs: Math, rhs: Math) -&gt; lhs.value + rhs.value \/\/ assuming value exists on Math somewhere\r\n}\r\n<\/pre>\n<p>We can also define custom operators, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nextension Math {\r\n  \/\/ prefix style op\r\n  static prefix func -&gt;&lt;- (value: Int) -&gt; Math\r\n}\r\n\r\n\/\/ in use\r\nlet x = -&gt;&lt;- 100\r\n<\/pre>\n<p><strong>Structs, Classes, Protocols &#038; Enums<\/strong><\/p>\n<p>I&#8217;m not going to spend too much time on these four types as they would take up a lot of space in this post (which is already long) but suffice to say we can create a struct, class, protocol and enum (an enum is more like the enums in Java than C# and is a type that may also include functionality). The syntax for each of these is pretty much as expected<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nstruct MyStruct {\r\n}\r\n\r\nclass MyClass {\r\n}\r\n\r\nenum MyEnum {\r\n}\r\n\r\nprocotol MyProtocol {\r\n}\r\n<\/pre>\n<p>A struct is a value type (as discussed previously) and can have properties, methods etc. Structs are heavily uses in Swift. A class is a reference type and as one would expect, can also have properties, methods etc. A protocol is similar to a C# interface bordering on an abstract type as it can contain default functionality.<\/p>\n<p>Enums are able to have values (options) as well as functionality, so here&#8217;s a simply example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nenum Color {\r\n    case red\r\n    case white\r\n    case blue\r\n    \/\/ ... etc.\r\n\r\n    func isRed() -&gt; Bool {\r\n        self == .red \/\/ .red shows abbreviated syntax\r\n    }    \r\n}\r\n<\/pre>\n<p><strong>Extensions<\/strong><\/p>\n<p>Swift also has the ability to create extension methods (as per C#). The extension method can be used on protocols, structs classes etc.<\/p>\n<p>If you&#8217;re used to C# extension methods then you&#8217;ll know that they allow us to extend frameworks or other libraries (as well as our own) which methods without the need to change the actual types themselves. The syntax for Swift extension is as follows<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nextension String {\r\n  func appendOne() -&gt; String {\r\n     return self + &quot;1&quot;\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Namespaces\/Modules<\/strong><\/p>\n<p>It appears that Swift does not (in this current release) have a concept of namespace or modules (or at least not as namespace like units). So what do we do?<\/p>\n<p>The most obvious way of duplicating a namespace (well to a point) is to host code within classes, structs or enums. In the case of a classes and structs we&#8217;d want to hide and make private the <em>init()<\/em> <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n@available(*, unavailable) private init() {}\r\n<\/pre>\n<p>With enums, if they do not contain cases then they cannot be instantiated, hence we can now just include the functions or whatever we want into an enum.<\/p>\n<p><strong>Exception handling<\/strong><\/p>\n<p>Swift uses a slightly different syntax to many other languages, it still has a <em>try<\/em> and a <em>catch<\/em> but the try does not wrap all code that may throw an exception. Exceptions in Swift are of type Error. So instead of wrapping code in a <em>try<\/em> block we wrap it in a <em>do<\/em> with <em>try<\/em> for specific lines, i.e.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\ndo {\r\n   let s = try getString()\r\n\r\n   \/\/ do something with s\r\n} catch MyError.StringError {\r\n   print('String Error occurred')   \r\n} catch MyError.SomeOtherError(let errorCode) {\r\n   print('Some Other Error occurred, error code: \\(errorCode)')   \r\n} catch {\r\n   print('Unhandled exception occurred \\(error)')\r\n}\r\n<\/pre>\n<p>In the above we declare our <em>do<\/em> block and our method <em>getString<\/em> potentially throws an error. We therefore <em>try<\/em> to call this method and if all is well, we&#8217;ll do something with the returns string. Otherwise we try to catch the error if it&#8217;s a MyError.StringError (some error we&#8217;ve previously declared in this case) otherwise the catch all takes care of things.<\/p>\n<p>What might our StringError look like? Well as Swift loves it&#8217;s enums, we&#8217;d potentially declare custom error conditions like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nenum MyError: Error {\r\n  case StringError\r\n  case SomeOtherError(errorCode: Int)\r\n}\r\n<\/pre>\n<p>Swift still uses the concept of throwing errors, so our method <em>getString<\/em> might look like this <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc getString() throws -&gt; String {\r\n   throw MyError.StringError   \r\n}\r\n<\/pre>\n<p>One neat feature Swift has around errors is that we can convert them to an optional, so for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet s = try? getString()\r\n<\/pre>\n<p>In this case if <em>getString<\/em> throws and error it&#8217;s converted to a nil. If, on the other hand we know that the method will not throw an error, for example maybe it throws an error if some member variable has not been set and we know it has been set, then we can disable error propogation using<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nlet s = try! getString()\r\n<\/pre>\n<p><strong>Generics<\/strong><\/p>\n<p>This &#8220;Swift basics&#8221; has a lot of topics, I&#8217;ve tried to reduce down to bare minimum of functionality most developers would look for or expect within a language. One last one feature we&#8217;ll cover is generics. <\/p>\n<p>As somebody who started using generics\/templates way back in my C++ days and was surprised at the lack of them in Java and C# in their early days and even Go today (if I recall). It&#8217;s nice to see Swift has generics and uses the fairly standard syntax of &lt;T&gt; (well in some ways fairly standard), i.e.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nfunc get&lt;T&gt;(index: Int) -&gt; T {\r\n   return someValue;  \r\n}\r\n<\/pre>\n<p>Swift doesn&#8217;t have the concept of <em>default(T)<\/em> like C#, so instead we would use nil (Optional.None).<\/p>\n<p>We can type constrain our generic parameters, for example if had an <em>add<\/em> method which should only work on <em>MyClass<\/em> types we would declare the method like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nmutating func add&lt;T: MyClass&gt;(item: T) -&gt; Void {\r\n}\r\n<\/pre>\n<p>Now, I said that Swift uses fairly standard syntax &#8220;well in some ways fairly standard&#8221;. The difference is when we declare protocols with, what&#8217;s called <em>Associated Types<\/em>. In the case of protocols we declare an <em>associatedtype<\/em> within the protocol, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nprotocol Container {\r\n  associatedtype Item\r\n  mutating func add(item: Item)\r\n  func get(index: Int) -&gt; Item\r\n}\r\n<\/pre>\n<p>When we come to implement the protocol we declare the type via the <em>typealias<\/em>, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nstruct MyContainer: Container {\r\n  typealias Item = MyClass\r\n\r\n  mutating func add(item: Item) {\r\n    \/\/ mutate something\r\n  }\r\n\r\n  get(index: Int) -&gt; Item {\r\n     \/\/ return something\r\n  }\r\n}\r\n<\/pre>\n<p>Ofcourse <em>MyContainer<\/em> itself might take generic parameters and hence we might have<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nstruct MyContainer&lt;T&gt;: Container {\r\n  typealias Item = T\r\n<\/pre>\n<p>And I think that&#8217;s more than enough for this post, other posts will probably focus more on specific parts of the language that are of interest.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A while back I looked into the Swift programming language but had so many other things on at the time that I didn&#8217;t get far with it, so let&#8217;s try again but from the basics. This post is the equivalent of a cheat sheet of the basics of Swift. Note: ofcourse there&#8217;s no way I [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[286],"tags":[],"class_list":["post-9015","post","type-post","status-publish","format-standard","hentry","category-swift"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/9015","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=9015"}],"version-history":[{"count":5,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/9015\/revisions"}],"predecessor-version":[{"id":9217,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/9015\/revisions\/9217"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=9015"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=9015"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=9015"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}