<?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 Greg Heo on Medium]]></title>
        <description><![CDATA[Stories by Greg Heo on Medium]]></description>
        <link>https://medium.com/@gregheo?source=rss-4c3430b2cdcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9ovJrHooE09PNjNAyxvYPg.png</url>
            <title>Stories by Greg Heo on Medium</title>
            <link>https://medium.com/@gregheo?source=rss-4c3430b2cdcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:14:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gregheo/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 Memory Layout: Size, Stride, Alignment]]></title>
            <link>https://medium.com/@gregheo/swift-memory-layout-size-stride-alignment-807cbf317361?source=rss-4c3430b2cdcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/807cbf317361</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Greg Heo]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 15:28:25 GMT</pubDate>
            <atom:updated>2018-03-16T15:28:25.866Z</atom:updated>
            <content:encoded><![CDATA[<h4>The basics on the memory layout of Swift struct instances.</h4><p>Swift types have three properties to consider when you’re dealing with them in memory: size, stride, and alignment.</p><h3>Size</h3><p>Let’s start with two simple structs:</p><pre>struct Year {<br> let year: Int<br>}</pre><pre>struct YearWithMonth {<br> let year: Int<br> let month: Int<br>}</pre><p>My intuition tells me that an instance of YearWithMonth is larger—it takes up more space in memory—than an instance of Year. But we’re scientists here; how can we verify intuition with hard numbers?</p><h3>Memory Layout</h3><p>We can use the MemoryLayout type to check some attributes around how our type looks in memory.</p><p>To find the size of a struct from its type, use the size property along with a generic parameter:</p><pre>let size = MemoryLayout&lt;Year&gt;.size</pre><p>If you have an instance of the type, use the size(ofValue:) static function:</p><pre>let instance = Year(year: 1984)<br>let size = MemoryLayout.size(ofValue: instance)</pre><p>In both cases, the size is reported as 8 bytes.</p><p>Not surprisingly, the size of our struct YearWithMonth is 16 bytes.</p><h3>Back to Size</h3><p>Size of a struct seems pretty intuitive — calculate the sum of each property’s size. For a struct like this:</p><pre>struct Puppy {<br> let age: Int<br> let isTrained: Bool<br>} </pre><p>The size should match the size of its properties:</p><pre>MemoryLayout&lt;Int&gt;.size + MemoryLayout&lt;Bool&gt;.size<br>// returns 9, from 8 + 1</pre><pre>MemoryLayout&lt;Puppy&gt;.size<br>// returns 9 </pre><p>Seems to work! [<em>Narrator: Or does it?</em> 😈]</p><h3>Stride</h3><p>The stride of a type becomes important when you’re dealing with multiple instances inside a single buffer, such as an array.</p><p>If we had a contiguous array of puppies, each one with a size of nine bytes, what would that look like in memory?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6YWqNP2CFABWJizU.png" /></figure><p>Turns out, not quite. ❌</p><p>The <em>stride</em> determines the distance between two elements, which will be greater than or equal to the size.</p><pre>MemoryLayout&lt;Puppy&gt;.size<br>// returns 9</pre><pre>MemoryLayout&lt;Puppy&gt;.stride<br>// returns 16</pre><p>So the layout actually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Avc82Fy_N1jkR9Lq.png" /></figure><p>That is, if you had a byte pointer to the first element and wanted to move to the second element, the stride is the number of bytes distance you’d need to advance the pointer.</p><p>Why would size and stride be different? That takes us to our final magic number of memory layout.</p><h3>Alignment</h3><p>Imagine the computer fetched eight bits, or one byte of memory at a time. Asking for byte 1 or byte 7 takes the same amount of time each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*OYsBB_3_wtfzJ1PF.png" /></figure><p>Then you upgrade to a 16-bit computer, which access data in 16-bit <em>words</em>. You still have old software that wants to access data by the byte but imagine the possible magic here: if the software asked for byte 0 and byte 1, the computer can now do a <strong>single</strong> memory access for word 0 and split up the 16-bit result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*GtKSB5XfzlNv9RFD.png" /></figure><p>Byte-level memory access is twice as fast in this ideal case! 🎉</p><p>Now say a rogue program put in a 16-bit value like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*NGuBSpMmh1ND1PFg.png" /></figure><p>Then you ask the computer for the 16-bit word at byte location 3. The problem is the value is <em>misaligned</em>. To read it, the computer needs to read the word at location 1, chop it in half, read the word at location 2, chop it in half, then paste the two halves together. That’s <em>two</em> separate 16-bit memory reads to access a single 16-bit value — twice as slow as it should be! 😭</p><p>On some systems, unaligned access is worse than slow — it’s not allowed entirely, and will crash the program.</p><h3>Simple Swift Types</h3><p>In Swift, the simple types such as Int and Double have the same alignment value as their size. A 32-bit (4 byte) integer has a size of 4 bytes and needs to be aligned to 4 bytes.</p><pre>MemoryLayout&lt;Int32&gt;.size      // returns 4<br>MemoryLayout&lt;Int32&gt;.alignment // returns 4 MemoryLayout&lt;Int32&gt;.stride    // returns 4</pre><p>The stride is also 4, meaning values in a contiguous buffer are 4 bytes apart. No padding needed.</p><h3>Compound Types</h3><p>Now back to our Puppy struct, which has an Int and a Bool property. Consider again the case where values are right up against each other in a buffer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tarmpPqY81zGWdsv.png" /></figure><p>The Bool values are happy where they are, since they have alignment=1. But the second integer is misaligned. It’s a 64-bit (8-byte) value with alignment=8 and its byte location is <em>not</em> on a multiple of 8. ❌</p><p>Remember the stride of this type was 16, meaning the buffer actually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vlYoFB1xx3ck3bIu.png" /></figure><p>We’ve preserved the alignment requirements of all the values inside the struct: the second integer is at byte 16, which is a multiple of 8.</p><p>That’s why the struct’s stride can be greater than its size: to add enough padding to fulfill alignment requirements.</p><h3>Calculating Alignment</h3><p>So here at the end of our journey, what is the Puppy struct type’s alignment?</p><pre>MemoryLayout&lt;Puppy&gt;.alignment // returns 8</pre><p>The alignment of a struct type is the <em>maximum</em> alignment out of all its properties. Between an Int and a Bool, the Int has a larger alignment value of 8, so the struct uses it.</p><p>The <strong>stride</strong> then becomes the <strong>size</strong> rounded up to the next multiple of the <strong>alignment</strong>. In our case:</p><ul><li>the size is 9</li><li>9 is not a multiple of 8</li><li>the next multiple of 8 after 9 is 16</li><li>therefore, the stride is 16</li></ul><h3>One Last Complication</h3><p>Consider our original Puppy and contrast it with AlternatePuppy:</p><pre>struct Puppy {<br> let age: Int<br> let isTrained: Bool<br>} // Int, Bool</pre><pre>struct AlternatePuppy {<br> let isTrained: Bool<br> let age: Int<br>} // Bool, Int </pre><p>The AlternatePuppy struct still has an alignment of 8 and stride of 16, but:</p><pre>MemoryLayout&lt;AlternatePuppy&gt;.size<br>// returns 16</pre><p>What?! All we did was change the order of the properties. Why is the size now different? It should still be 9, shouldn’t it? A Bool followed by an Int, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*qv-Ba-wJD3BBiSxS.png" /></figure><p>Maybe you see the problem here: the 8-byte integer is no longer aligned! What this actually looks like in memory is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*ankoALXjpsxZs85P.png" /></figure><p>The struct itself has to be aligned <em>and</em> the properties inside the struct have to stay aligned. The padding moves in between elements, and the size of the overall struct expands.</p><p>In this case, the stride is still 16 so the effective change from Puppy to AlternatePuppy is the position of the padding. What about these structs?</p><pre>struct CertifiedPuppy1 {<br> let age: Int<br> let isTrained: Bool<br> let isCertified: Bool<br>} // Int, Bool, Bool</pre><pre>struct CertifiedPuppy2 {<br> let isTrained: Bool<br> let age: Int<br> let isCertified: Bool<br>} // Bool, Int, Bool</pre><p>What are the size, stride, and alignment for these two structs? 🤔 (<a href="https://gist.github.com/gregheo/00ffc980a9d28a5f3aa0371b12b65150">spoiler</a>)</p><h3>The Closing Brace</h3><p>In the end, say you have an UnsafeRawPointer (aka a void * in C). You know the type of thing it points to. Where do size, stride, and alignment come into the picture?</p><ul><li><strong>Size</strong> is the number of bytes to read from the pointer to reach all the data.</li><li><strong>Stride</strong> is the number of bytes to advance to reach the next item in the buffer.</li><li><strong>Alignment</strong> is the the “evenly divisible by” number that each instance needs to be at. If you’re allocating memory to copy data into, you need to specify the correct alignment (e.g. allocate(byteCount: 100, alignment: 4)).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2100ggnrvzPCBVy-.png" /></figure><p>For most of us, most of the time, we probably deal with high-level collections such as arrays and sets and don’t need to consider the underlying memory layout.</p><p>In other cases, you work with lower-level APIs on the platform or interop with C code. If you have an array of Swift structs and need your C code to read it (or vice versa) you’ll need to worry about allocating a buffer with the correct alignment, making sure padding <em>inside</em> the struct lines up, and making sure you have the right stride value so you can interpret the data correctly.</p><p>And as we saw, even calculating size isn’t as simple as it seems — there’s some interplay between the size and alignment of each property that determines a struct’s <em>overall</em> size. So understanding all three means you’re on your way to being a master of memory.</p><p>}</p><p><em>Originally published at </em><a href="https://swiftunboxed.com/internals/size-stride-alignment/"><em>swiftunboxed.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=807cbf317361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift’s Numeric Protocol]]></title>
            <link>https://medium.com/@gregheo/swifts-numeric-protocol-7af87d228948?source=rss-4c3430b2cdcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7af87d228948</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftlang]]></category>
            <category><![CDATA[numeric]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Greg Heo]]></dc:creator>
            <pubDate>Tue, 07 Nov 2017 15:26:00 GMT</pubDate>
            <atom:updated>2017-11-07T15:26:00.646Z</atom:updated>
            <content:encoded><![CDATA[<p>I was at <a href="https://www.jessesquires.com/">Jesse Squires</a>’s talk at <a href="http://iosconf.sg/">iOS Conf Singapore</a>, where he discussed <a href="https://speakerdeck.com/jessesquires/exploring-swifts-numeric-types-and-protocols">Swift’s numeric types and protocols</a>. That reminded me of <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0104-improved-integers.md">SE-0104, Protocol-oriented integers</a> and now that the implementation is in Swift 4, thought it would be a good time to have a closer look.</p><p>Let’s start with the protocol hierarchy for Int, everyone’s favorite integer type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CjPSC5uG1M_J8q9x.png" /></figure><p>As with most types in the standard library, Int conforms to a whole lot of protocols! All the way down the chain, Numeric is one of the base protocols. All the different sized integer types (UInt, Int8, etc.) as well as floating-point types (Float, Double, etc.) conform to Numeric.</p><h3>Numeric, Starting From 0x00</h3><p>You can follow along with the standard library source in <a href="https://github.com/apple/swift/blob/master/stdlib/public/core/Integers.swift.gyb">Integers.swift.gyb</a>, although as usual, all the relevant code will be inline below.</p><p>Here’s the protocol declaration to start:</p><pre>public protocol Numeric : Equatable, ExpressibleByIntegerLiteral {</pre><p>Two additional conformances here:</p><ul><li>Equatable adds support for the == operator.</li><li>ExpressibleByIntegerLiteral allows for code like let a: Int = 42 where 42 is the aforementioned “integer literal”.</li></ul><p>That means all numeric types can be initialized with integer literals but not float literals. This bit of code is OK:</p><pre>let someFloat: Float = 42 // ✅</pre><p>But this is not OK:</p><pre>let someInt: Int = 4.2 // 🙅</pre><p>You’ll run into the ExpressibleByFloatLiteral protocol in specific floating-point types, but not at the level of general Numeric types.</p><h3>Initialization</h3><p>The protocol has one required initializer:</p><pre>init?&lt;T : BinaryInteger&gt;(exactly source: T)</pre><p>It’s a failable initializer, and the “exactly” in the argument label should tell you why: if you try to initialize an instance with a value beyond what it can hold, the initializer will return nil:</p><pre>let ok = Int8(exactly: 10) // 10<br>let tooBig = Int8(exactly: 300) // nil</pre><p>Also note the constraint on the source type: it has to conform to BinaryInteger. BinaryInteger conforms to Numeric so it seems a little weird for a “parent” protocol like Numeric to need a type that conforms to a “child” protocol like BinaryInteger to construct itself. What’s going on here?</p><h3>Representation vs Use</h3><p>A quick sidebar on exactly what these two protocols BinaryInteger and Numeric are for.</p><p>According to the header docs, BinaryInteger is just what it says on the tin: “An integer type with a binary representation”. That’s pretty familiar to many programmers as we use integers measured in bits all the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*xWYh0kqmAeeImKFb.png" /></figure><p>Numeric, on the other hand, isn’t so much about representation as it is about <em>usage</em>. The protocol “provides a suitable basis for arithmetic on scalar values”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*4tCOnoKADWDQw72Y.png" /><figcaption>Everyone’s favorite arithmetic operations.</figcaption></figure><p>OK, back to arithmetic then. 🤓</p><h3>Magnitude</h3><p>Magnitude is the absolute value of the number, so 42.magnitude and -42.magnitude are both 42.</p><pre>associatedtype Magnitude : Comparable, Numeric<br>var magnitude: Magnitude { get }</pre><p>The magnitude computed property has to be Numeric and also Comparable. That means a number itself doesn’t have to be comparable, but its magnitude does.</p><p>When you look at the concrete implementation of types such as Int, you’ll see it uses magnitude to do some arithmetic, calculate distance between numbers, etc.</p><h3>Arithmetic</h3><p>We’ve reached our favorite arithmetic operation: addition!</p><pre>static func + (_ lhs: Self, _ rhs: Self) -&gt; Self<br>static func +=(_ lhs: inout Self, rhs: Self)</pre><p>The first addition function takes two values and produces the sum; the second is the <em>mutating</em> version where the “left hand side” argument (the a in a += 10) is mutated.</p><p>In your own numeric types, you should at a minimum provide the implementation for the mutating operators.</p><p>If you’ve coded types that conform to Equatable, you’ll remember you need to provide an implementation for == and then you get != for free.</p><p>Similarly, the usual pattern is to define + in terms of +=. For example, the implementaton of + in the concrete standard library type UInt16 uses +=:</p><pre>// Inside the UInt16 implementation<br>public static func +(_ lhs: UInt16, _ rhs: UInt16) -&gt; UInt16 {<br>  var lhs = lhs<br>  lhs += rhs<br>  return lhs<br>}</pre><p>Finally, the Numeric protocol also requires operators for subtraction and multiplication:</p><pre>static func - (_ lhs: Self, _ rhs: Self) -&gt; Self<br>static func -=(_ lhs: inout Self, rhs: Self)</pre><pre>static func * (_ lhs: Self, _ rhs: Self) -&gt; Self<br>static func *=(_ lhs: inout Self, rhs: Self)</pre><p>Same guidelines apply, where you should provide the mutating version for your own conforming types.</p><h3>Things Left Unsaid</h3><p>Concrete numeric types do much more than what’s defined here in this one protocol. As you saw from the diagram at the top of this post, there are a lot of protocols put together to make something as complex as a Swift integer.</p><p>That said, we’ve only covered Numeric and seen just a slice of all the functionality we’re used to from a numeric type. What are some of the big things missing?</p><ul><li><strong>Division</strong> — we’ve seen addition, subtraction, and mulitplication, but what of the missing arithmetic family member? Division is defined separately in the BinaryInteger and FloatingPoint protocols.<br>The function definitions in the protocols are the same, but the specs are slightly different: integer division discards the remainder, and floating-point division follows the <a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE-754</a> rules.</li><li><strong>Floating-point things</strong> — you saw how types that conform to Numeric are also ExpressibleByIntegerLiteral but not expressible by float literals. Integers can be converted to floats in a straightforward manner, but you need to consider rounding when going from float to integer. How should this rounding work? That’s something out of scope for Numeric.</li><li><strong>Comparable</strong> — again, this is something found on the BinaryInteger and FloatingPoint protocol level, except for the magnitude property you saw earlier. Both those protocols conform to Strideable, which in turn implies Comparable.</li></ul><h3>The Closing Brace</h3><p>The Numeric protocol provides the fundamentals of numeric types:</p><ul><li>Initialization with integer values</li><li>Equatable</li><li>Simple arithmetic</li><li>The concept of a <em>magnitude</em> to determine its underlying value</li></ul><p>In addition to the missing things listed in the previous section, the protocol also has no opinion on <em>storage</em>. Remember, Numeric is about what numbers are <em>used</em> for, while the other protocols down the line such as BinaryInteger are about <em>representation</em> and how the values are stored.</p><p>Ready to build your own custom <a href="https://en.wikipedia.org/wiki/Vigesimal">vigesimal</a> numeric type yet? 😉</p><p>}</p><p><em>Originally published at </em><a href="https://swiftunboxed.com/protocols/numeric/"><em>swiftunboxed.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7af87d228948" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON with Encoder and Encodable]]></title>
            <link>https://medium.com/@gregheo/json-with-encoder-and-encodable-46e3010917cc?source=rss-4c3430b2cdcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e3010917cc</guid>
            <category><![CDATA[encodable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Greg Heo]]></dc:creator>
            <pubDate>Thu, 29 Jun 2017 03:45:11 GMT</pubDate>
            <atom:updated>2017-06-29T03:45:11.044Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift 4 brings a more native-feeling way to encode and decode instances, and includes built-in support for everyone’s favorite text-based format: JSON!</p><p>Rather than pore through all the source code for encoding and decoding, let’s take a different approach and step through a simple example: how does a single Int instance wind its way through JSONEncoder and become JSON data?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kdgKdYUsPyt7vJM6.png" /></figure><p>From there we should be able to take a step further and understand how other primitive types, arrays, dictionaries, etc. are encoded.</p><h3>Archiving</h3><p>NSCoding has been storing and retrieving data as part of Cocoa for a long time. In some exciting news, Apple has finally announced the deprecation of NSArchiver now that NSKeyedArchiver has been available for 15 years. 😜</p><p>The big idea is if individual instances such as strings and numbers can be <em>encoded</em> and <em>decoded</em>, then you can <em>archive</em> and <em>unarchive</em> entire object graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2ZNARpKpIQH5fq8U.png" /></figure><h3>Encoding All The Things</h3><p>In the Swift standard library, there are things that are <em>encodable</em> as well as <em>encoders</em>.</p><ul><li><strong>Encodable</strong> is a protocol. A conforming type can encode itself to some other representation.</li><li><strong>Encoder</strong> is also a protocol. Encoders do the work of turning Encodable things to other formats such as JSON or XML.</li></ul><p>Encodable is like NSCoding but as a Swift protocol, your Swift structs and enums can join the party too. Similarly, Encoder is the counterpart to NSCoder although Encoder is again a protocol rather than an abstract class.</p><h3>One Simple Integer</h3><p>You can’t encode a bare scalar using JSONEncoder, but need a top-level array or dictionary instead. For simplicity, let’s start with encoding an array containing a single integer, [42].</p><pre>let encoder = JSONEncoder()<br>let jsonData = try! encoder.encode([42])</pre><p>First we instantiate JSONEncoder and then call encode() on it with our array. What’s going on in there?</p><pre>// JSONEncoder.swift<br>open func encode&lt;T : Encodable&gt;(_ value: T) throws -&gt; Data {<br>  let encoder = _JSONEncoder(options: self.options)</pre><p>The encode() method takes some Encodable value and returns the raw JSON Data.</p><p>The actual encoding work is in the private class _JSONEncoder. This approach keeps JSONEncoder as the type with the friendly public interface, and _JSONEncoder as the fileprivate (everyone’s favorite!) class that implements the Encoder protocol.</p><pre>  // continued from above<br>  try value.encode(to: encoder)</pre><p>Note the reversal: at the original call site, we asked the <em>encoder</em> to encode a value; here, the encoder asks the <em>value</em> to encode itself <strong>to</strong> the private encoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*-Dii0kiB-TbWllSG.png" /></figure><h3>Encodable</h3><p>Let’s take a step back and look at the relevant parts of the protocols at play here.</p><p>First up is Encodable — remember, this is the protocol for the <em>values</em> such as integers and arrays that can be encoded.</p><pre>public protocol Encodable {<br>  func encode(to encoder: Encoder) throws<br>} </pre><p>We’ll gloss over the wrapping array [42] and just consider the integer value 42 to keep things simple. Int conforms to Encodable and we can have a look at what its encode(to:) method does:</p><pre>extension Int : Codable {<br>  public func encode(to encoder: Encoder) throws {<br>    var container = encoder.singleValueContainer()<br>    try container.encode(self)<br>  }<br>} </pre><p>We’re asking the encoder for a container, then asking that container to encode self, the integer value.</p><h3>Encoder</h3><p>Our next sidebar is to discuss Encoder — this is the protocol for classes such as _JSONEncoder that do the heavy lifting of turning encodable values into some coherent format.</p><pre>public protocol Encoder {<br>  // [...]<br>  func container&lt;Key&gt;(keyedBy type: Key.Type) -&gt; KeyedEncodingContainer&lt;Key&gt;<br>  func unkeyedContainer() -&gt; UnkeyedEncodingContainer<br>  func singleValueContainer() -&gt; SingleValueEncodingContainer<br>}</pre><p>At their core, encoders can deal with three kinds of values thanks to the three accessor methods above:</p><ol><li>Keyed containers (dictionaries)</li><li>Unkeyed containers (arrays)</li><li>Single-value containers (for scalar values)</li></ol><p>Back to the code to encode an Int:</p><pre>// extension Int : Codable<br>var container = encoder.singleValueContainer()<br>try container.encode(self)</pre><p>First, get a single-value container from the JSON encoder, which is this code here:</p><pre>// _JSONEncoder<br>func singleValueContainer() -&gt; SingleValueEncodingContainer {<br>  return self<br>} </pre><p>Well that’s simple: _JSONEncoder itself conforms to SingleValueEncodingContainer and returns itself. Let’s take a quick peek at that protocol:</p><pre>public protocol SingleValueEncodingContainer {<br>  // [...]<br>  mutating func encode(_ value: Int) throws<br>}</pre><p>There are many additional encode methods for all kinds of simple types such as Bool, String, etc. But the one we’re interested in is for Int:</p><pre>// extension _JSONEncoder : SingleValueEncodingContainer<br>func encode(_ value: Int) throws {<br>  assertCanEncodeNewValue()<br>  self.storage.push(container: box(value))<br>}</pre><p>It’s the moment of truth! There’s some kind of storage, and we’re pushing a boxed value onto it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hgBa8aNEMcoC0MFY.png" /></figure><p>But what’s the storage? And what’s with the box? 🤔</p><h3>Storage</h3><p>To understand the storage, let’s jump ahead to the end. We’re way down in the stack here, but do you remember how we started? It was the encode() method in JSONEncoder where we passed in the array with one integer. The final line of that method looks like this:</p><pre>// JSONEncoder.swift<br>return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions) </pre><p>So the whole point of it all is to have a top-level container (an array or dictionary) that gets passed to JSONSerialization, formerly known as NSJSONSerialization.</p><p>The storage is another fileprivate struct that keeps a stack of containers. Beware, Objective-C will start to show itself here:</p><pre>fileprivate struct _JSONEncodingStorage {<br>  /// The container stack.<br>  /// Elements may be any one of the JSON types<br>  /// (NSNull, NSNumber, NSString, NSArray, NSDictionary).  <br>  private(set) var containers: [NSObject] = []<br>}</pre><p>So that explains the box. Our array [42] will turn into an NSMutableArray and the box() call above will turn the integer into an NSNumber that gets added to the array:</p><pre>// extension _JSONEncoder<br>fileprivate func box(_ value: Int) -&gt; NSObject {<br>  return NSNumber(value: value)<br>}</pre><p>Turns out if you go deep enough, it’s Objective-C all the way down.</p><p>To summarize: our Swift values get turned into their Foundation object equivalents by JSONEncoder and friends, then these objects get JSON-ified by JSONSerialization.</p><h3>The Closing Brace</h3><p>Here’s the final set of steps on asking JSONEncoder to encode the array with a single integer, [42]:</p><ol><li>Array, encode yourself <em>to</em> _JSONEncoder</li><li>Array sets up unkeyed container (NSMutableArray storage)</li><li>Array iterates over all elements and encodes them</li></ol><p>a. Integer, encode yourself to _JSONEncoder</p><p>b. Integer sets up single-value container</p><p>c. Integer asks the container to encode itself</p><ul><li>Container boxes the integer into NSNumber, adds to the array</li></ul><p>7. Use JSONSerialization to encode the top-level NSMutableArray</p><p>8. Profit! 💰</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kxOZIEH9j2vih5fX.png" /></figure><p>You can find all the relevant code in <a href="https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift">JSONEncoder.swift</a> and <a href="https://github.com/apple/swift/blob/master/stdlib/public/core/Codable.swift">Codable.swift</a> in the standard library source.</p><p>Now what about the reverse, decoding? And how can you write custom encoders and decoders for formats other than JSON, say protocol buffers? Stay tuned for more, or why not dig into the code and see what you find?</p><p>}</p><p><em>Originally published at </em><a href="https://swiftunboxed.com/stdlib/json-encoder-encodable/"><em>swiftunboxed.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e3010917cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce]]></title>
            <link>https://medium.com/@gregheo/reduce-a83c85f07960?source=rss-4c3430b2cdcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a83c85f07960</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[mapreduce]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-playgrounds]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Greg Heo]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 16:08:13 GMT</pubDate>
            <atom:updated>2017-04-06T16:09:23.895Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Filter, reduce, and map:<br>Collections transformed at a tap.<br> These functional friends,<br> your code they will cleanse,<br>with immutable inputs, no trap.</blockquote><p>Map and filter get a lot of attention, but I say reduce is the important one. Or if you’re interested in efficiency, how about this: you can <em>build</em> map and filter using reduce. If you’re going to learn about just one, pick reduce.</p><h3>Functional Friends</h3><p><a href="https://swiftunboxed.com/open-source/map/">Map</a> has the useful behavior of performing some operation on every item in the sequence and collecting the results.</p><pre>let words = [&quot;hello&quot;, &quot;there&quot;]<br>let shoutyWords = words.map { $0.uppercased() }<br>// [&quot;HELLO&quot;, &quot;THERE&quot;]</pre><p>The input to map is a sequence of size <em>n</em>, and the output will also be of size <em>n</em>.</p><p>Next, filter lets you decide which items to keep (and which to discard) from a sequence.</p><pre>let numbers = 0...10<br>let evenNumbers = numbers.filter { $0 % 2 == 0 }<br>// [0, 2, 4, 6, 8, 10]</pre><p>The output size will be somewhere between 0 and <em>n</em>, depending on how many things get filtered.</p><p>What of reduce?</p><h3>Reducing Reduce</h3><p>Like the other two operations, reduce takes a sequence as input but its output is more generic: it can be anything you want!</p><p>For every turn of the loop, reduce passes the previous output along with the current item. That means you get a some state preserved between iterations and can build up the output however you need it.</p><p>For the first time through, you need to provide an initial starter “result” value. That means reduce takes two arguments:</p><ol><li>The initial result value.</li><li>A closure that produces the next partial result.</li></ol><p>Reduce will pass in the partial result and next value as arguments to the closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FoyddbzF3KbbGx-E.png" /><figcaption>Reduce: initial value, closure for each item, loop, final value</figcaption></figure><h3>Using Reduce</h3><p>The textbook example of reduce is finding the sum of numbers:</p><pre>let primes = [3, 7, 31, 127]<br>let sum = primes.reduce(0) { (result, item) in<br>  return result + item<br>}</pre><p>The first time through, reduce will call closure(0, 3) where 0 is the initial value and 3 is the first item. The result is now 0 + 3, or 3.</p><p>The next time through the loop, reduce will call closure(3, 7) where 3 is the result from last time and 7 is the next item. And so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ymT-6B6w_eYxQZepI04_EA.gif" /><figcaption>Sum via reduce animation</figcaption></figure><p>At the end, we’ll have turned an array [Int] into the final result of type Int.</p><h3>Building Reduce</h3><p>Let’s have a look at how reduce is built in the standard library. As usual, the code will be inline below and you can see the code yourself on GitHub in <a href="https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb">SequenceAlgorithms.swift</a>.</p><p>It’s pretty short once you get through the slightly gnarly function signature:</p><pre>public func reduce&lt;Result&gt;(<br> _ initialResult: Result,<br> _ nextPartialResult:<br>  (_ partialResult: Result, Iterator.Element) throws -&gt; Result )<br> rethrows -&gt; Result {</pre><p>There are a lot of Result types here — that’s the generic type describing what the final return value will be. This can be different from Iterator.Element, which is the type of the thing in the sequence.</p><p>The initialResult parameter is of type Result, and needs to be passed into the function as the first argument.</p><p>The second parameter is the closure that runs for each value in the sequence. The closure itself gets passed two arguments:</p><ol><li>The result returned from the previous iteration.</li><li>The next item in the sequence.</li></ol><p>Finally, the throws and rethrows keywords allow for closures that throw errors; these will be rethrown up the chain to the original caller if needed.</p><h3>Accumulating Results</h3><p>The accumulator variable will hold the cumulative result as we iterate through the sequence.</p><pre>var accumulator = initialResult</pre><p>We’ll start out with the initial result passed into the function.</p><p>Next up is the big iteration step:</p><pre>for element in self {<br>  accumulator = try nextPartialResult(accumulator, element)<br>}</pre><p>The accumulator gets replaced each time through the loop with the new partial value returned from the closure. Again, the closure here takes the previous result and the next element.</p><p>Just one more line to go:</p><pre>return accumulator</pre><p>By the end, all that’s left to do is return the last result.</p><h3>Building Map</h3><p>How might you build map with reduce? For simplicity, we’ll work with arrays rather than sequences.</p><p>Let’s think about map in terms of how reduce works:</p><ul><li>The result type will be an array</li><li>The initial value should be an empty array</li><li>For each turn of the loop, add an item to the array</li></ul><pre>extension Array {<br>  func mapUsingReduce&lt;OutElement&gt;(<br>   _ closure:<br>   (_ item: Iterator.Element) -&gt; OutElement) -&gt; [OutElement] {<br>    return self.reduce([]) { (partial, item) in<br>      return partial + [closure(item)]<br>    }<br>  }<br>}</pre><p>The generic parameter OutElement is the type of element in the output array. The method takes a closure to perform the transform step of converting an Iterator.Element into an OutElement.</p><p>The reduce call is as expected here: start with an empty array, and keep adding to the accumulated array each time through the loop.</p><p>Can you think of how to write filter using reduce? How about sort? What other uses can you think of? How efficient is doing map this way vs actual map?</p><h3>The Closing Brace</h3><p>This is one of those times where learning how to use a hammer means every problem starts looking like a nail (to wrangle another turn of phrase). Whenever I need some kind of operation on an array, I start thinking of how I might do it with reduce.</p><p>That doesn’t mean I actually <em>use</em> reduce though — it isn’t the best solution for every problem! What I like about it is it makes me think through the basics: initial value, an incremental step, and how to slowly build up a return value.</p><p><em>Download </em><a href="http://swiftunboxed.com/downloads/Reduce.playground.zip"><em>Reduce.playground</em></a><em> to check out the code and play around with it yourself.</em></p><p>}</p><p><em>Originally published at </em><a href="http://swiftunboxed.com/lang/reduce/"><em>swiftunboxed.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a83c85f07960" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Unbelievable Secrets of Reactive Programming the Experts Don’t Want You to Know!]]></title>
            <link>https://medium.com/@gregheo/five-unbelievable-secrets-of-reactive-programming-the-experts-dont-want-you-to-know-911f36024de1?source=rss-4c3430b2cdcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/911f36024de1</guid>
            <category><![CDATA[rxcocoa]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[reactivex]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Greg Heo]]></dc:creator>
            <pubDate>Sun, 26 Feb 2017 19:24:07 GMT</pubDate>
            <atom:updated>2017-03-01T18:11:54.308Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Based on a talk given at </em><a href="http://www.playgroundscon.com/"><em>Playgrounds</em></a><em> in Melbourne, February 24, 2017.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*__440sEB_LSCxJLl.png" /></figure><p>I was asked to come up with a <a href="https://twitter.com/playgroundscon/status/811685860110307328">super click-baity title</a> for the talk and here it is: <strong>Five Unbelievable Secrets of Reactive Programming the Experts Don’t Want You to Know!</strong></p><p>(Exactly <em>why</em> the experts don’t want you to know these things is still unclear to me.)</p><p>I’ve heard it said about learning Lisp or Prolog or functional programming — even though you might never use Lisp again, learning the language and how it works will (supposedly) change the way you think about writing code and change the way you design programs.</p><p>Does the same thing apply to reactive programming? It did for me; writing apps with RxSwift highlighted some best practices and architectural choices that I already knew about, but are much more at the forefront when thinking in the reactive style.</p><p>These aren’t actually “secrets” per se, but more like “big picture ideas” that solidified in my head as I learned more about reactive programming. Read on to find out what they are!</p><h3>1. You already know it</h3><p>The good news is you already know the pieces that make up reactive programming.</p><p>If you’re writing iOS apps in the “traditional” Cocoa style and you learn about functional programming, you already know what a function is. It’s more about learning a new style, a new way of thinking, and perhaps some new words such as everyone’s favorite, “monad”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bSbwC0fmLwdvv1b0.png" /></figure><p>Same goes for reactive programming: you’ll see old concepts like sequences, closures, and map used in familiar but novel ways. The way they’re put together, and the language used to describe it may be new but the building blocks are the same.</p><h3>2. Everything is a sequence</h3><p>The first thing I think about when designing an app in the reactive style is: what are the sequences? I like to split them into two big categories, inputs and outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mvXt6hEekneurk_X.png" /></figure><p>Thanks to extensions on common classes provided by RxCocoa, you get many of these sequences, or <strong>observables</strong> included out of the box.</p><p>For example, UISlider has an observable providing a sequence of Float values. UIButton has an observable that fires every time the button is tapped.</p><p>You can make your own observables too. I wrote one for a Mac app, to keep track of mouse clicks. NSViewController receives a mouseDown(with:event)method call whenever there’s a mouse click on the view. You can have RxCocoa listen for that method call, and turn that into an observable:</p><pre>self.rx.sentMessage(#selector(NSResponder.mouseDown(with:)))<br>  .map({ (params) -&gt; NSPoint? in<br>    if let event = params.first as? NSEvent {<br>      return self.view.convert(event.locationInWindow, from: nil)<br>    }<br>    return nil<br>  })</pre><p>In this case, the first line sets up an observable that produces a value every time mouseDown(with:) gets called. Then we can map over that observable (which remember, is just a sequence) and produce an output observable of NSPoint values.</p><h3>3. Small pieces of logic</h3><p>In the example above, we had a sequence of events that needed to be transformed into a sequence of points. Each of these transformations pushes the data through your app.</p><p>Within the big box that is your application, there are smaller sequences within.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJQ1jRSEmHqPz9c-.png" /></figure><p>Each step along the way is its own operation, looking something like another map with a closure. This structure means your programs can be made of small, discrete pieces of logic rather than monolithic massive view controllers.</p><h3>4. Declarative style</h3><p>With all these sequences floating around, how do you get them connected together to perform useful work? Up until now, we’ve only seen sequences transformed into other sequences.</p><p>Another useful thing you can do with observables is <em>subscribe</em> to them. That means whenever there’s a new value available, or something else happens such as an error or the observable completes, you can provide a closure to react to it.</p><p>In the simplest case, say you have an observable that produces strings coming in from some source such as the network. You could subscribe to this observable, and set the value of a label.</p><pre>someStringObservable .subscribe(onNext: { (stringValue: String) in<br>  self.label.text = stringValue<br>})</pre><p>As a shortcut, you could use the <em>bind</em> function and take advantage of more RxCocoa extensions:</p><pre>someStringObservable .bindTo(self.label.rx.text)</pre><p>The magic rx property provides properties that can be read or written to. A text field, for instance, can be bound to but you could also subscribe to changes since they accept user input.</p><p>The magic comes once you’ve set up all your observables, maps, subscriptions, and bindings: at that point, you can start up your application and all the pieces are magically connected together. Thanks to the declarative approach, you’ve set up the logic of all the transformations and relationships and can now wait for input to start flowing through.</p><h3>5. Testable code</h3><p>Having logic in small discrete pieces means they also become easy to test.</p><p>Take a very simple example: a class that takes as its input an observable that produces integers:</p><pre>class SomeController {<br>  // Input observable providing a sequence of integers<br>  var intObservable: Observable&lt;Int&gt;</pre><pre>  init(intObservable: Observable&lt;Int&gt;) {<br>    self.intObservable = intObservable<br>  }<br>}</pre><p>It has a computed property that transforms the input integers into strings:</p><pre>extension SomeController {<br>  // Output observable that converts the integers to strings<br>  var stringConversionObservable: Observable&lt;String&gt; {<br>    return intObservable .map({ (intValue: Int) -&gt; String in<br>      return String(intValue)<br>    })<br>  }<br>}</pre><p>You want to test this out. In your app, intObservable comes from some place, maybe the network, maybe user input—it doesn’t really matter. All you want to test is the <em>conversion</em> operation. In this case, the conversion logic is simple but you can imagine having a map with more complex business logic in there.</p><p>Between a sequence of integers and a sequence of strings, how are we going to mock these things? If only there were some easy way to mock an ordered, iterable sequences of integers, right? 🤔</p><p>At this point, I hope you’re thinking of arrays. Yes, you could take an input <em>array</em> of integers, push that through the observable, and get an output array of strings:</p><pre>// Test input data<br>let input = [1, 2, 42]</pre><pre>// Turn the array into an observable<br>let inputObservable = Observable.from(input)</pre><pre>// Initialize the controller with our test observable<br>let controller = SomeController(intObservable: inputObservable)</pre><p>Observables are usually asynchronous since you can’t tell when a value will be available ahead of time. Since this is a test with a fixed array, we can turn this into a <em>blocking observable</em> so it waits for the map to complete synchronously.</p><pre>// Thanks to the toArray() call, this will be an regular array of strings<br>let output = try! controller.stringConversionObservable.toBlocking().toArray()</pre><p>Then it’s a simple matter of making sure the output matches what you expected.</p><pre>let expectedOutput = [&quot;1&quot;, &quot;2&quot;, &quot;42&quot;]<br>XCTAssert(output == expectedOutput)</pre><p>Done! The nice thing about having inputs and outputs modeled as sequences is that when we need to mock them in tests, it’s very easy to do so thanks to arrays.</p><h3>Beyond the five secrets</h3><p>After learning the basics of reactive programming, these “five secrets” encapsulate some big ideas about software architecture and how I want to structure my code. I’m thinking more in terms of streams of data and small blocks of testable code.</p><p>If you want to learn more about RxSwift, I’d suggest the following resources:</p><ul><li><a href="https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md">RxSwift Getting Started page</a></li><li><a href="http://rx-marin.com/">rx-marin</a> — excellent articles with lots of RxSwift example code</li><li><a href="http://reactivex.io/">ReactiveX.io</a> — language- and platform-neutral guide to the Rx style of programming</li></ul><p>If you were at the Playgrounds talk and want to check out some resources from the talk:</p><ul><li>Sample Noughts &amp; Crosses game <a href="https://github.com/gregheo/NoughtsAndCrosses">source code</a></li><li><a href="https://speakerdeck.com/gregheo/five-unbelievable-secrets-of-reactive-programming-the-experts-dont-want-you-to-know">Slides from the talk</a></li></ul><p><em>Originally published at </em><a href="https://gregheo.com/blog/reactive-programming-basics/"><em>gregheo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911f36024de1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open-source Swift: Booleans]]></title>
            <link>https://medium.com/@gregheo/open-source-swift-booleans-8aae7c87037b?source=rss-4c3430b2cdcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aae7c87037b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[boolean]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Greg Heo]]></dc:creator>
            <pubDate>Wed, 09 Dec 2015 17:31:48 GMT</pubDate>
            <atom:updated>2015-12-09T17:31:48.915Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I wrote about the <a href="http://swiftunboxed.com/protocols/BooleanType/">BooleanType</a> <a href="http://swiftunboxed.com/protocols/">protocol</a>. Now that we have <a href="https://swift.org/">open-source Swift</a>, it’s time to look at the mother of all BooleanType types: Bool itself!</p><h3>Close reading</h3><p>Rather than the usual computer science or physics or philosophy background of most developers, I was an English major. We spent a good amount of time doing <em>close readings</em> of prose passages and poetry.</p><p>I thought, why not put all that education to good use and try something similar for code?</p><p>After all — Prose : Documentation :: Poetry : Code, right?</p><h3>Bool.swift</h3><p>The code is all inline below, but you can see the original file in the Swift repository too: <a href="https://github.com/apple/swift/blob/master/stdlib/public/core/Bool.swift">Bool.swift</a>.</p><p>I picked a seemingly simple example to start as a good way into the Swift standard library source code for me. Let’s get started!</p><pre>/// A value type whose instances are either `true` or `false`. public struct Bool {</pre><p>No surprise, it’s a struct. I still hear from many people who are amazed at the heavy use of value types, but Swift is massively tilted in that direction: <a href="https://gregheo.com/blog/switching-your-brain-to-swift/#value-types">structs outnumber classes by a factor of 20</a> in the standard library.</p><h3>Storage</h3><pre>internal var _value: Builtin.Int1</pre><p>Here’s the actual storage: a one-bit integer. We’ll presumably get 1 for true and 0 for false.</p><p>Builtin means the thing is coming from “one layer down”. If you’ve looked into <a href="http://swiftc.io/post/132002781944/hello-sil">SIL</a>, you’ll see this all over the place when it digs down to the LLVM layer.</p><p>In this case, Int1 should map to the LLVM type of the same name further down the line.</p><p>In terms of style, they’re using a leading underscore for non-public properties. Also, note that the property is internal rather than private; that means other modules in the standard library can access this bit directly when needed.</p><h3>Initializers</h3><pre>/// Default-initialize Boolean value to `false`.<br>@_transparent<br>public init() {<br>  let zero: Int8 = 0<br>  self._value = Builtin.trunc_Int8_Int1(zero._value)<br>}</pre><p>Here’s the public initializer. By default, Bool instances get a default value of false.</p><p>There are some minor acrobatics here to get a zero value into the _value property. While Swift has a native Int8 to go with the Builtin.Int8, there’s no native Int1.</p><p>To get that one-bit zero, the strategy here is to start with an Int8. From there, there’s another handy Builtin to truncate the 8-bit value to a 1-bit value.</p><p>Of course trunc_Int8_Int1 takes a Builtin.Int8 rather than a Swift Int8. As with Bool, Int8 has a _value property to access the raw built-in value. And since it’s internal rather than private, we have access to it here!</p><p>What’s @_transparent? Here’s a note from <a href="https://github.com/apple/swift/blob/master/docs/TransparentAttr.rst">the documentation</a>:</p><blockquote><em>Semantically, @_transparent means something like “treat this operation as if it were a primitive operation”. The name is meant to imply that both the compiler and the compiled program will “see through” the operation to its implementation.</em></blockquote><p>Check out the docs for the gory details, but think of @_transparent functions as unchanging inlined functions that don’t rely on private or internal details.</p><pre>@_transparent <br>internal init(_ v: Builtin.Int1) { self._value = v }</pre><p>Here’s the second initializer, with a more common structure: it takes a Builtin.Int1 and assigns it directly to the _value property. This initializer is internal-only, which makes sense since only the standard library code will have easy access to Builtin.Int1 values anyway.</p><h3>BooleanLiteralConvertible</h3><pre>extension Bool : _BuiltinBooleanLiteralConvertible, BooleanLiteralConvertible {<br>  @_transparent<br>  public init(_builtinBooleanLiteral value: Builtin.Int1) {<br>    self._value = value<br>  }</pre><pre>  /// Create an instance initialized to `value`.<br>  @_transparent<br>  public init(booleanLiteral value: Bool) { self = value }<br>}</pre><p>Bool conforms to BooleanLiteralConvertible and its more private counterpart _BuiltinBooleanLiteralConvertible.</p><p>Nothing too surprising here: the protocols have required initializers and they’re implemented here: one that takes a literal Builtin.Int1 and the other that takes a Bool.</p><p>There’s some duplication here since we’ve already seen an initializer that takes a Builtin.Int1 value. They have different external parameter names and one is internal vs public, but the implementations are identical.</p><h3>BooleanType</h3><pre>extension Bool : BooleanType {<br>  @_transparent <br>  @warn_unused_result<br>  public func _getBuiltinLogicValue() -&gt; Builtin.Int1 {<br>    return _value<br>  }</pre><pre>  /// Identical to `self`.<br>  @_transparent <br>  public var boolValue: Bool { return self }</pre><pre>  /// Construct an instance representing the same logical value as `value`.<br>  public init&lt;T : BooleanType&gt;(_ value: T) {<br>    self = value.boolValue<br>  }<br>}</pre><p>Bool should, of course, conform to BooleanType, which has one required property: boolValue. That needs to return a Bool which makes the implementation here very simple: return self.</p><p>There are two additional things here in the extension:</p><ul><li>_getBuiltinLogicValue() — returns that internal Builtin.Int1 value of the Bool, which seems to break encapsulation. I can only find <a href="https://github.com/apple/swift/blob/master/test/SILPasses/recursive_func.sil#L36">two</a> <a href="https://github.com/apple/swift/blob/master/test/SILPasses/recursive_single.sil#L38">instances</a> where the method is called in the standard library code, both in the set of SIL tests.</li><li>Another initializer that takes anything that conforms to BooleanType. That makes sense: you should be able to initialize a Bool from any such BooleanType.</li><li>@warn_unused_result makes its first appearance. That’s what triggers the “Result of call is unused” warning you see in Xcode.</li></ul><h3>CustomStringConvertible</h3><pre>extension Bool : CustomStringConvertible {<br>  /// A textual representation of `self`.<br>  public var description: String { return self ? &quot;true&quot; : &quot;false&quot; }<br>}</pre><p>Playground users and people debugging their code all around the world will love you forever if you remember to implement CustomStringConvertible for your types.</p><h3>Magic conversion</h3><pre>// This is a magic entrypoint known to the compiler.<br>@_transparent public // COMPILER_INTRINSIC<br>func _getBool(v: Builtin.Int1) -&gt; Bool { return Bool(v) }</pre><p>It’s <em>magic</em>!</p><p>Intrinsic functions are indeed magic since the compiler will have special knowledge of them.</p><p>In this case, the function is a shortcut to turn one of those Builtin.Int1 values into a Bool using the initializer we’ve already seen.</p><p>This function is @_transparent and will be inlined away — as will the initializer, come to think of it. It’s inlining all the way down!</p><h3>Hashable</h3><pre>@_transparent <br>extension Bool : Equatable, Hashable { <br>  public var hashValue: Int { return self ? 1 : 0 }<br>}</pre><p>Best practice for value types is to make them Equatable and Hashable.</p><p>For Equatable, you need to provide an implementation for ==, which you’ll see in a bit.</p><p>For Hashable, you need to hash the value down to an Int. That’s easy in this case: true is 1 and false is 0.</p><h3>Unary logical complement</h3><pre>@_transparent <br>@warn_unused_result <br>public prefix func !(a: Bool) -&gt; Bool {<br>  return Bool(Builtin.xor_Int1(a._value, true._value))<br>}</pre><p>We’re coming to the end, which must mean: more public functions!</p><p>Here’s the ! operator to turn true into false and vice versa. The obvious solution to toggle the bit might be something like this:</p><pre>return a ? false : true</pre><p>But think back to bitwise operations instead. How do you toggle a bit? XOR it with 1, of course! That’s what’s happening here: xor_Int1 with the argument’s value and the Int1 representation of true.</p><p>I guess when you go way down to assembly, this will become a plain old XOR instruction, which is super fast. Contrast that to the obvious implementation, which has a branch.</p><blockquote><em>Trivia note from the early x86 days: XOR’ing a register with itself (XOR AX, AX) was the fastest way to zero out the value since the instruction was shorter than MOV AX, 0.</em></blockquote><h3>Equatable</h3><pre>@_transparent <br>@warn_unused_result <br>public func ==(lhs: Bool, rhs: Bool) -&gt; Bool {<br>  return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value))<br>}</pre><p>Here’s the == operator to make Equatable happy.</p><p>Again, the implementation uses a built-in to compare the Int1 values directly. Perhaps this will compile down to a CMP in assembly to again be super fast?</p><h3>Final thoughts</h3><p>That was a lot of words for a relatively simple type!</p><p>Lifting up the covers of a fundamental type such as Bool offers plenty of coding tips and implementation details. Some highlights:</p><ul><li><strong>Two-space tabs</strong> — That’s spaces, not tabs. I feel like I would fit right into the Swift team in case you’re reading, Apple. ;)</li><li><strong>Protocols</strong> — Type functionality is split up by protocol to keep things organized.</li><li><strong>Extensions</strong> — Each protocol conformance is in its own extension. I’ve used that style since the Objective-C days and am glad to see it here too.</li><li><strong>Built-ins</strong> — In contrast to C, Swift is more levels above the metal: in the LLVM workflow, you’re going from Swift to SIL to LLVM IR to machine code. Built-ins are a neat way to move down one level and let a lower-level implementation know your intentions so it can optimize accordingly.</li></ul><p>There’s what I like best about open-source: getting below the surface and seeing how things work.</p><p>I hope this was useful and a fun read! Share, let me know what you think, and in the meantime I plan to keep poking around the source.</p><p><em>Originally published at </em><a href="https://swiftunboxed.com/open-source/Bool/"><em>swiftunboxed.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aae7c87037b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>