<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeffrey Thompson on Medium]]></title>
        <description><![CDATA[Stories by Jeffrey Thompson on Medium]]></description>
        <link>https://medium.com/@jeffreythompson_52867?source=rss-36ae8352218e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Jeffrey Thompson on Medium</title>
            <link>https://medium.com/@jeffreythompson_52867?source=rss-36ae8352218e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:11:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeffreythompson_52867/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift Types & Type Safety: Intuition for Beginners]]></title>
            <link>https://medium.com/@jeffreythompson_52867/swift-types-type-safety-intuition-for-beginners-c12a6dd7f5ad?source=rss-36ae8352218e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12a6dd7f5ad</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jeffrey Thompson]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 14:48:28 GMT</pubDate>
            <atom:updated>2024-09-19T14:48:28.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*rWfqnq7TJJhxV_nQOgZ1Uw.png" /></figure><h3>Why Type Safety Matters</h3><p>In Swift, you can’t just throw types together and expect the compiler to “figure it out.” An example:</p><pre>let a = 1.0<br>let b = 1<br>let c = a + b // !!! Compiler error !!!<br>// Binary operator &#39;+&#39; cannot be applied to operands of type &#39;Double&#39; and &#39;Int&#39;</pre><p>Why? Swift is strict about type safety, meaning Int and Double cannot be combined without explicit conversion. While this might seem annoying at first, it’s a safeguard to prevent subtle bugs from creeping into your code.</p><p>We have to care about types because we <em>kinda</em> need to care about the hardware our software is running on. It touches on the more meta question of: what is computing? A great way to get a good answer to that question is to go watch a YouTube video from the people who build rudimentary computers on bread boards. But for here and now, a basic (over)simplification: computing is storing state in transistors as electrical charges (bits of 1s and 0s in the programmer’s vernacular) and executing operations on those bits.</p><p>Transistors don’t know what an Int or a String is. Individually they know I have a charge or I don’t have a charge. AKA “on” or “off” — a bit. A byte knows a collection of 8 “on/off” bits. But giving meaning to those 1s and 0s belongs in the domain of the programming language.</p><p>The inability to add Double and Int can be frustrating, not being able to add UInt8 and UInt16 even more so. The novice programmer will reason: they’re both numbers, add them already! That’s fine for a human brain because synapses != transistors. “Four” == 4 == 4.0 == IV == “Quattro”, this works just fine in our noggin because we’re smarter than we realize we are. Computers are different though — they’re stuck making sense of an array of 1s and 0s and the listed variants of the number four would be completely incomparable. So let’s get visual.</p><h3>Why Can’t Int and UInt8 Play Nicely?</h3><p>Swift has a variety of number types — Int, UInt8, Int64, and more—each occupying different amounts of memory. But combining these types isn’t as simple as it seems. For instance, adding a UInt8 to a UInt16 doesn’t work because the two types store their data in different-sized memory spaces.</p><p>Imagine the classic Reversi (Othello) board game as an analogy for how data is stored in memory. Imagine the occupied tiles of the 64 square (bit) board represent the transistors allowed for a given data type, and the discs legend is 0 = black, 1 = white.</p><h4>UInt8 — Integer, unsigned, 8 bits</h4><pre>let num: UInt8 = 4 // 0b00000100<br>UInt8.min // 0<br>UInt8.max // 255</pre><p>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>⚫️⚫️⚫️⚫️⚫️⚪️⚫️⚫️</p><h4>UInt16 — Integer, unsigned, 16 bits</h4><pre>let num: UInt16 = 4 // 0b0000000000000100<br>UInt16.min // 0<br>UInt16.max // 65535</pre><p>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>🟩🟩🟩🟩🟩🟩🟩🟩<br>⚫️⚫️⚫️⚫️⚫️⚫️⚫️⚫️<br>⚫️⚫️⚫️⚫️⚫️⚪️⚫️⚫️</p><p>So, why can’t we add UInt8 and UInt16? Because 0b1001_1101 + 0b0110_1011_0010_0100 would lead to overflow. UInt6 uses twice as much memory as UInt8. The extra 8 bits go… where? Try adding the “8bit” and the “16bit” Reversi boards together. How does that work? Answer: it doesn’t. It’s an undefined behavior. Does it overflow UInt8 and just wrap around from zero? As in, “Okay so we got to 255, let’s start at zero again.” Some languages do work like that. However in those languages the developer must know this and remember this for every occasion, never letting an instance slip through where they forgot. That leads to bugs (try Googling: “c integer overflow check”).</p><p>The Swift compiler acts like a pedantic DMV clerk that simply says “Nope, against rules and regulations. Go fill out the form to cast one of the types and get back in line”. This helps, but even this approach isn’t perfect as overflow can still happen in Swift, but instead of just “making it work” somehow, Swift encounters a runtime error. Once again, runtime error, AKA “Crash” is assumed by the beginner to be “bad”. However, defined crashes are infinitely better than undefined, undetected, AKA exploitable behavior.</p><h3>Signed vs Unsigned: special symbol bits.</h3><p>The above examples are all <strong>unsigned integers</strong>, positive value integers. With a <strong>signed integer</strong>, the first bit is reserved for the sign, indicating whether the number is positive or negative. This means an Int8 can represent values from -128 to 127, while a UInt8 (unsigned) can store values from 0 to 255. Here’s a look at how the two types compare:</p><h4>Int8 — Integer, signed, 8 bits</h4><pre>let a = Int8(bitPattern: 0b01111111) // 127<br>let b = Int8(bitPattern: 0b11111100) // -4<br>let c = Int8(bitPattern: 0b00000100) // 4<br>let d = Int8(bitPattern: 0b10000000) // -128</pre><p>⚫️⚪️⚪️⚪️⚪️⚪️⚪️⚪️ -&gt; 127<br>⚪️⚫️⚫️⚫️⚫️⚫️⚫️⚫️ -&gt; -128</p><p>Adding UInt8 and Int8 directly doesn’t work because the first bit in a signed integer is interpreted differently than in an unsigned one.</p><h3>Floating-Point: another special symbol bit.</h3><p>Floating-point types like Double and Float introduce yet another layer of complexity. They have special bits that “float” the decimal point to accommodate very large or very small numbers. Trying to mix a floating-point number with an integer without converting them first leads to an error, as they store and interpret data very differently.</p><pre>let a: Double = 4.0<br>let b: Int = 4<br>// let c = a + b // Error: Type mismatch</pre><p>Explicit conversion is required:</p><pre>let c = a + Double(b)</pre><h3>Strings: It’s all just numbers? Always has been.</h3><p>Strings in Swift may seem straightforward, but they, too, are governed by types. Originally, characters were mapped to numbers via the ASCII table. Today, we use more advanced systems like UTF-8 and UTF-16, but the basic concept is the same: a string is just an array of characters, each represented by numbers under the hood. Those numbers, however, are strictly embedded in their types. As such, “4” most definitely does not == 0b0000_0100.</p><pre>let scalarAry = &quot;Hello, world!&quot;.flatMap({ $0.unicodeScalars.map(\.value)<br>})<br>print(scalarAry)<br>// [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]</pre><h3>Conclusion: Understanding Types to Write Better Code</h3><p>Swift’s strict type system may feel like a hurdle at first, but it’s there to protect you. By making you specify types and requiring explicit conversions, it prevents subtle, hard-to-find bugs caused by unchecked operations or type mismatches. Whether you’re dealing with integers, floating-point numbers, or strings, understanding how data is stored and manipulated at a low level will make you a more effective, thoughtful programmer.</p><p>So, the next time you’re frustrated by Swift refusing to add an Int to a Double, or any other seamingly simple conversion is denied, remember that this is by design. The compiler isn’t being difficult—it’s helping you avoid the pitfalls of mixing incompatible types. And as you deepen your understanding of types and how they relate to hardware, you’ll appreciate the safeguards Swift puts in place to keep your code clean and predictable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12a6dd7f5ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Optionals, Intuition for Beginners]]></title>
            <link>https://medium.com/@jeffreythompson_52867/swift-optionals-intuition-for-beginners-4084bbe22379?source=rss-36ae8352218e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4084bbe22379</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift-optionals]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jeffrey Thompson]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 16:24:41 GMT</pubDate>
            <atom:updated>2023-11-22T16:24:41.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optionals are a Pringles can.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RboQ6JbSUUTfec_l" /><figcaption>Photo by <a href="https://unsplash.com/@lmahammad?utm_source=medium&amp;utm_medium=referral">Lal MAHAMMAD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Wut?</p><p>Bear with me. Imagine you’re back in elementary school. Your mother, who graciously packed your lunch, added in some homemade chocolate chip cookies. You are the envy of your classmates. A notoriously unscrupulous classmate, the local bully, asks if you’d like to trade an entire Pringles can for your cookies. Hmm. That’s a lot of Pringles. Do you trade?</p><p>What do you think? What does the can contain? Pringles! 🤩 Or… Pringles? 🤔</p><p>You’re really not sure. A trade with an untrustworthy business partner is a risk. An empty container accompanied by cruel laughter is well within the range of possibility. The only thing you know with absolute certainty is you would be getting a <em>package</em> which may or may not contain the thing you actually want — salty snacks with no nutritional value. You don’t eat Pringles cans. You don’t consume Optionals.</p><h3>Package != contents.</h3><p>This analogy can be extended and mutated ad nauseam.</p><p><strong>Recipe Analogy:</strong> You have guests coming for dinner. Dessert recipe calls for milk. You have a milk carton in the fridge. Carton contains… Milk! or Milk? Unless you have a perfect memory, you need to check and then account for the possibility there is no more milk. Substitute, or go buy more.</p><p><strong>Product purchase analogy:</strong> You are in charge of IT purchasing for your company. A developer needs a new MacBook. You find a deal on Craigslist. You hand over some company cash and have a MBP box handed to you. You come back to the office and open it up. You expect a… MacBook Pro! But if you got swindled, well your career just crashed and you got fired. Had you purchased directly from an Apple Store, then yes, expecting a brand new shiny MackBook Pro! upon unboxing would have been reasonable. Shady Craigslist ad? Not so much.</p><p>Hopefully this gives the intuition for the underlying implementation and syntactic sugar that is associated with Swift Optionals.</p><p><strong>Real life encounters:</strong> You get plenty of “packages” from APIs that may or may not contain a value.</p><pre>{<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;middle_name&quot;: null,<br>  &quot;last_name&quot;: &quot;Doe&quot;<br>}</pre><p>The above JSON is a common example of where an API may return null data and is one of the many use cases for Optionals in Swift. Other use cases may include attempting to cast types from one to another.</p><pre>let aInt: Int? = Int(&quot;a&quot;) // aInt will be nil<br>let twoInt: Int? = Int(&quot;2&quot;) // twoInt will have a value of 2<br><br>// however both are still the same Type<br>print(type(of: aInt)) // Optional&lt;Int&gt;<br>print(type(of: twoInt)) // Optional&lt;Int&gt;</pre><p>In the above snippet Swift effectively says “you can try, but I can’t guarantee success”. Note that aInt is not of type nil just as twoInt is not of typeInt. Both are of type Optional which has an associated type of Int. Type Optional has two states.</p><h3>A stately problem</h3><p>A package with contents needs to be unwrapped to get to the contents. A package with no contents will simply be empty upon unwrapping and you move on to plan B.</p><p>Our package analogy has two states. Has something. Has nothing. And when dealing with finite states in computer science what is our favorite data type? Enumerations.</p><p>A Pringles can is an enum. Okay, I stretched that analogy a bit too far, but it can be modeled as an enum in Swift due to Swift’s wonderful feature of associated values in enums.</p><pre>enum PringlesCan { <br>  case has(Pringles)<br>  case empty<br>}</pre><p>And this is exactly how Optionals are defined in Swift (albeit with generics). <a href="https://github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift">Go have a peek under the hood.</a></p><pre>enum Optional&lt;Wrapped&gt; { <br>  case some(Wrapped)<br>  case none<br>}<br><br>var nilInt: Int? // auto assigns nil val.<br>var nilIntTwo: Int? = nil // exact same as above<br>var nilIntThree = Optional&lt;Int&gt;.none // exact same as above<br><br>var valInt: Int? = 42 // still an Optional, NOT an Int<br>var valIntTwo = Optional&lt;Int&gt;.some(42) // exact same as above</pre><p>Understanding this implementation also helps us understand the syntactic sugar that Swift adds to the Optional type. When declaring a type as String? (an alias for: Optional&lt;String&gt;) — the only thing being declared is a package that may or may not contains its desired contents. For the beginner, the verbose form is actually more instructive and therefore more intuitive. It’s easy to recognize that type Optional&lt;String&gt;.some is not equal to type String. It is less intuitive to view the syntactic sugar forms and realize String? != String. But just keep thinking: Package != Contents.</p><h3>Milk carton != milk.</h3><p>Milk? is an inappropriate item type for a recipe. It needs actual <em>milk</em>, not a <em>milk carton</em> thrown into the mixing bowl.</p><pre>var milkCarton: Milk? // or: Optional&lt;Milk&gt;.none<br><br>func pourMilk() { <br>  if let milk = milkCarton { <br>    recipe.add(milk)<br>  } else { <br>    goToStore()<br>  }<br>}</pre><p>if let is an unwrapping method. guard let / if varsame concept, different use cases. In plain English the function is: “Let’s open the carton and see. If it’s there, great, let’s use it. If not, well we need to do something else.” milk is an unwrapped value. Like milk poured from a carton into a mixing bowl, it is no longer considered a carton. Therefore milk is of type Milk , not type Optional&lt;Milk&gt;.</p><p>Another useful unwrapping method is the ?? operator.</p><pre>let milk = milkCarton ?? meltedButter</pre><p>The ?? operator allows you to use a defined default value in the case of Optional.None also known as nil.</p><h3>Bang! is as dangerous as it sounds</h3><p>Some beginners are tempted to simply employ the Bang! operator to get the cranky Swift compiler to shut up. This is the operator that will forcefully unwrap an Optional without checking its contents first. This can be appropriate in certain instances, such as expecting that a brand new MacBook Pro box directly from the Apple Store does indeed contain a new MacBook Pro. However, unless you are guaranteed this kind of absolute certainty, the habit of using the bang! operator will quickly lead to issues.</p><pre>func pourMilk { <br>  recipe.add(milk!) // The carton is empty. There is no milk. <br>                    // Your recipe failed and you will never<br>                    // live down the embarrassment. <br>                    // Your social life is now over.<br>}</pre><p>Don’t ruin your social life. Don’t crash your apps either. Unwrap your packages, look inside, and have a contingency if what you want isn’t there. Hopefully this gives an intuition into the concept of Optionals in Swift and said intuition will change your view of the Swift compiler from pedantic antagonist bent on thwarting your code progress to best friend that saves you from serving gag-inducing desserts and making a fool of yourself.</p><p>Have fun out there. And even if they don’t technically conform to Equatable, homemadeChocolateChipCookies &gt; Pringles so please just ignore trade inquiries from the schoolyard bully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4084bbe22379" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>