<?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 Faisal Bin Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Faisal Bin Ahmed on Medium]]></description>
        <link>https://medium.com/@Faisalbin?source=rss-347760846b14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xfYaqusQVJ_RkeZZkU8Wfg.jpeg</url>
            <title>Stories by Faisal Bin Ahmed on Medium</title>
            <link>https://medium.com/@Faisalbin?source=rss-347760846b14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:01:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Faisalbin/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[Philosophy of storing union type collection in TypeScript, Swift, and Rust]]></title>
            <link>https://medium.com/@Faisalbin/philosophy-of-storing-union-type-collection-in-typescript-swift-and-rust-078a7c95afce?source=rss-347760846b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/078a7c95afce</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Faisal Bin Ahmed]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 22:00:24 GMT</pubDate>
            <atom:updated>2024-04-17T17:23:48.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SSTIbZ602ZJSyvOcUwAAg.jpeg" /><figcaption>Drew my own logos; hopefully Rust Foundation won’t sue me</figcaption></figure><h3>Can you create TypeScript style mixed arrays in Swift / Rust?</h3><p>One really useful feature of TypeScript or most other garbage-collected languages is the ease of storing values of arbitrary size and shape to a list.</p><p>Let’s say I want to store an object SingleRow that has a property called rowData. rowData can store any of 4 possible types of values. These types are of different shapes and sizes.</p><p>For example below, we can store values of a union type RowData to the SingleRow object’s rowData property. Since RowData can be any of the following 4 types, this rowData can hold values of different sizes. If you only program in a language like JavaScript/TS, you might not give it a second thought. And neither did I for many years.</p><pre><br>enum RowType {<br>  spacer, header, data, sum<br>}<br><br>type DataRow = {<br>  // can hold anything<br>}<br>type SumRow = {<br>  // can hold different things -&gt; different sizes in memory<br>}<br>type SpacerRow = {}<br>type HeaderRow = {}<br><br><br>type RowData = DataRow | SumRow | SpacerRow | HeaderRow;<br><br>type SingleRow = {<br>  id: number;<br>  rowType: RowType;<br>  rowData: RowData; // rowData can be of varying size and type<br>}<br><br>let rows: Array&lt;SingleRow&gt; = [];</pre><p>Since behind the scenes, it all transpiles down to a plain JS object and objects in Javascript can hold values of any type &amp; size, we don’t get any compiler error. If you’re interested, this is how it looks in JS:</p><pre>&quot;use strict&quot;;<br>var RowType;<br>(function (RowType) {<br>    RowType[RowType[&quot;spacer&quot;] = 0] = &quot;spacer&quot;;<br>    RowType[RowType[&quot;header&quot;] = 1] = &quot;header&quot;;<br>    RowType[RowType[&quot;data&quot;] = 2] = &quot;data&quot;;<br>    RowType[RowType[&quot;sum&quot;] = 3] = &quot;sum&quot;;<br>})(RowType || (RowType = {}));<br>let rows = [];</pre><h3>Swift</h3><p>Now let’s try the same with Swift, a strong and strictly typed language.</p><p>Swift won’t let us do this, it doesn’t have a concept of union type. But there are at least 2 ways we can achieve similar functionality:</p><h4>Enum associated values</h4><pre>struct HeaderRow {<br>    var label: String = &quot;&quot;<br>}<br>struct SumRow {}<br>struct SpacerRow {}<br>struct DataRow {<br>    var label: String<br>    var description: String?<br>    var value: Double<br>}<br><br>enum RowData {<br>    case dataRow(DataRow)<br>    case headerRow(HeaderRow)<br>    case sumRow(SumRow)<br>    case spacerRow(SpacerRow)<br>}<br><br>struct SingleRow {<br>    let id: UUID<br>    let rowData: RowData<br>}<br><br>var dummyRows: [SingleRow] = [<br>    SingleRow(id: UUID(), rowData: .sumRow(SumRow())),<br>    SingleRow(id: UUID(), rowData: .headerRow(HeaderRow(label: &quot;Expenses&quot;))),<br>    SingleRow(id: UUID(), rowData: .dataRow(DataRow(label: &quot;Rent&quot;, description: &quot;House rent&quot;, value: 900))),<br>    SingleRow(id: UUID(), rowData: .spacerRow(SpacerRow())),<br>]</pre><p>This looks similar-ish, we can store arbitrary types of data in the same field of a struct. i.e. in the rowData field, we can assign an enum variant, and each of those enum variants has associated values of different types.</p><p>This solves our problem then, right? Not quite.</p><p>At some point, we would like to mutate the underlying values of those associated types. Swift makes it really hard to mutate them; each time we have to create an instance of the DataRow() or get a reference to it, and finally mutate that to reassign the instance object to the rowData field with the correct enum variant.</p><p>While this is doable, this makes the job extremely unergonomic.</p><pre>dummyRows[1].rowData.label = &quot;Not Expenses&quot;<br>// this is not possible<br>// you cann not simply access the underlying associated value of an enum</pre><p>Another solution is to <a href="https://www.objc.io/blog/2018/03/13/mutable-self/">write a method as an extension to our enum type</a> to call it with a value and variant every time we want to mutate an enum object directly. Then again, we have to implement a switch case to do it. Not terrible, not good either. I’m pretty sure there are other solutions to this problem, but they all require a lot of syntactic sugar.</p><p><em>Disclaimer: I am talking about ergonomics here.</em></p><h4>Protocols</h4><pre>protocol SingleRow {<br>    var id: UUID { get }<br>    var rowType: RowType { get }<br>}<br>// Enum to represent the different row types<br>enum RowType {<br>    case data, spacer, sum, header<br>}<br>// Implement structs conforming to the SingleRow protocol<br>struct DataRow: SingleRow {<br>    var id = UUID()<br>    let rowType: RowType = .data // this makes sure we can force type cast it with as! DataRow safely<br>    var label: String = &quot;&quot;<br>    var value: Double = 0<br>    var description: String?<br>}<br>struct SpacerRow: SingleRow {<br>    var id = UUID()<br>    let rowType: RowType = .spacer<br>}<br>struct HeaderRow: SingleRow {<br>    var id = UUID()<br>    let rowType: RowType = .header<br>    var title: String<br>}<br>struct SumRow: SingleRow {<br>    var id = UUID()<br>    let rowType: RowType = .sum<br>}<br><br>// pay attention to the `any` keyword here<br>var dummyRows: [any SingleRow] = [<br>    HeaderRow(title: &quot;Expenses&quot;),<br>    DataRow(label: &quot;Rent&quot;, value: 900),<br>    DataRow(label: &quot;Transport&quot;, value: 90),<br>    DataRow(label: &quot;Internet&quot;, value: 49),<br>    DataRow(label: &quot;Groceries&quot;, value: 200),<br>    SpacerRow(),<br>]</pre><p>We declare a protocol (like an interface in TS or trait in Rust) with the common properties we want in all our subtypes. In this case, it only has 2 common and mandatory fields: an ID and a rowType enum. Any classes or structs implementing the protocol SingleRow must have these fields, other than that, the world is your canvas. You can attach any kind of field to each child struct and an array containing a set of subtypes conforming to the protocol will still work, even though each array element may be of different size.</p><p>The caveat here is the any keyword. any refers to an <a href="https://www.hackingwithswift.com/swift/5.6/existential-any">existential type</a> of values in Swift. This will — in a nutshell — create an array of generic types that conform to the protocol SingleRow. <em>Not to be confused with Typescript’s </em><em>any keyword.</em></p><p>When we create a Swift array of [any SingleRow] type where SingleRow is a protocol, the underlying data type is different than a homogenous array of SingleRow such as Swift doesn’t know what concrete type each element holds. Since Swift 5.7 by assigning any keyword we explicitly tell the compiler to perform <strong>dynamic dispatch</strong> on our existential data type.</p><p>However, this comes with a cost: in terms of runtime overhead and developer experience. More about the runtime cost later.</p><p>For example: If we want to use an array of existential types to iterate and display the values with SwiftUI Foreach, we can not readily do that. The compiler will complain that any SingleRow must conform to the Identifiable protocol. Depending on your subclass, this can be pretty easy to downright pain in the a**. I tried to do just that but ended up refactoring my SingleRow struct to not use inheritance at all.</p><h3>Rust</h3><p>Let’s see how we can do the same in my favorite language. Rust doesn’t support inheritance but we can achieve similar features in 3 ways: enum association, composition, and using traits.</p><h4>Enum associated values</h4><pre>enum RowType {<br>    Data(DataRow),<br>    Sum(SumRow),<br>    Header(HeaderRow),<br>    Spacer(SpacerRow)<br>}<br><br>struct DataRow {<br>    id: u32<br>}<br>struct SpacerRow{}<br>struct HeaderRow{}<br>struct SumRow{}<br><br>fn main() -&gt; () {<br><br>    let data_row = RowType::Data(DataRow{id: 1});<br>    let spacer_row = RowType::Spacer(SpacerRow{});<br><br>    let array_of_different_rows: Vec&lt;RowType&gt; = vec![data_row, spacer_row];<br>    <br>}</pre><p>We define an enum called RowType with 4 possible variations. Each variant holds a different struct themselves. These structs in turn hold values of different shapes and sizes.</p><p>In the main function, we create a vector of type RowType ; this vector (similar to an array in other languages) can hold any number of enum variants. Since vectors are a smart pointer storing the actual values in the heap, the size can grow. Also, the size of each element — the enum variant — stays consistent. Each <a href="https://www.eventhelix.com/rust/rust-to-assembly-enum-match/#:~:text=Memory%20layout%20of%20a%20Rust%20enum&amp;text=The%20total%20memory%20needed%20for,currently%20saved%20in%20the%20enum.">variant’s size depends on the largest of the bunch</a> but they are the same. The Rust compiler is happy.</p><p>While this implementation satisfies our requirement — and I will personally use this — what if we want to add some common fields or features to the individual struct types?</p><p>What we are describing is inheritance; Rust does not support inheritance like other OOP languages, but we can achieve similar functions with composition and traits.</p><h4><strong>Composition</strong></h4><p>Let’s say all of the row structs need to have some specific fields: id and value. One way to achieve this is by composition. We can define a base struct field called common_fields that is not optional and of type CommonFields.</p><pre>struct SingleRow {<br>    id: u32,<br>}<br>enum RowType {<br>    Data(DataRow),<br>    Sum(SumRow),<br>    Header(HeaderRow),<br>    Spacer(SpacerRow)<br>}<br><br>struct CommonFields {<br>    id: u32,<br>    value: Option&lt;i64&gt;<br>}<br><br>struct DataRow {<br>    common_fields: CommonFields,<br>    // other fields<br>    <br>}<br>struct SpacerRow{<br>    common_fields: CommonFields,<br>}<br>struct HeaderRow{}<br>struct SumRow{}<br><br>fn main() -&gt; () {<br><br>    let a_data_row = RowType::Data(DataRow{common_fields: CommonFields{id: 1, value: Some(0)}});<br>    let a_spacer_row = RowType::Spacer(SpacerRow{common_fields: CommonFields{id: 2, value: None}});<br><br>    let array_of_different_rows: Vec&lt;RowType&gt; = vec![a_data_row, a_spacer_row];<br>    <br>}</pre><p>Compared to our previous solution, now we dictate each variant of the enum to have some common properties defined in the struct CommonFields. Hence we cannot create an enum variant without specifying an id.</p><p>But what if we don’t want to use enums for this what about polymorphism? What if we want all of our row structs to have specific methods? This is where traits come in.</p><h4>Trait</h4><p>Traits are used when we want structs that conform (or implement) our trait to all have specific methods available to them. When we attach</p><p>#[derive(Clone)] on top of a struct, Rust will automatically implement the Clone trait on our struct, as a result, we get all the methods specified on the Clone trait for free.</p><p>Now let’s create a SingleRow trait specifying all methods we want our rows structs to have.</p><pre>trait SingleRow {<br>    fn get_id(&amp;self) -&gt; u32;<br>}<br><br>struct DataRow {<br>    id: u32<br>}<br><br>impl SingleRow for DataRow {<br>    fn get_id(&amp;self) -&gt; u32 {<br>        self.id<br>    }<br>}<br><br>struct SpacerRow {<br>    id: u32<br>}<br><br>impl SingleRow for SpacerRow {<br>    fn get_id(&amp;self) -&gt; u32 {<br>        self.id<br>    }<br>}<br><br>struct HeaderRow{}<br>struct SumRow{}<br><br>fn main() -&gt; () {<br><br>    let a_data_row = DataRow{id: 1};<br>    let a_spacer_row = SpacerRow{id: 2};<br><br>    let array_of_different_rows: Vec&lt;Box&lt;dyn SingleRow&gt;&gt; = vec![Box::new(a_data_row), Box::new(a_spacer_row)];<br>    <br>}</pre><p>A few things to note in the above implementation: Box and dyn.</p><p>Since we are storing Vec&lt;SingleRow&gt; and SingleRow is not a concrete type like a struct but a trait, we do not know the size of each trait object at compile time (each struct can have a different number of fields/methods), hence we need a smart pointer called Box. Box gives us 2 crucial features that allow us to store our trait objects in a vector:</p><ol><li>it stores objects in the heap, and</li><li>the size of the object is known at compile time. (<em>vector elements have to be of fixed size</em>)</li></ol><p>As for dyn, we explicitly tell the rust compiler to use dynamic dispatch (a runtime feature) on our trait object to derive the methods associated with each trait object at runtime.</p><p><strong>Dynamic dispatch</strong> uses a vtable to <a href="https://www.eventhelix.com/rust/rust-to-assembly-static-vs-dynamic-dispatch/#:~:text=Rust%20supports%20two%20types%20of,not%20known%20at%20compile%20time.">map each concrete type and all its method pointers at runtime</a>. As a result, there is a runtime cost associated with it (<em>multiple pointer de-referencing per call</em>).</p><p>With <strong>Static dispatch</strong>, we don’t get any runtime cost. The compiler knows which structs call the specific functions, so in compile time, it creates different static functions (with known parameter types) adhering to each concrete type that calls the said function. This is how generic works in other languages (as well as Rust.)</p><pre>// static dispatch version of a function that returns id<br>fn get_id(row: &amp;impl SingleRow) -&gt; u32 {<br>    return row.get_id();<br>}<br>// dynamic dispatch version of the same function<br>fn get_id_dyn(row: &amp;dyn SingleRow) -&gt; u32 {<br>    return row.get_id();<br>}</pre><p>But why can’t we static dispatch here when creating the vector? With <strong>trait objects, we have to use dynamic dispatch</strong> because, at compile time, rust doesn&#39;t know how many other structs implemented this trait and all the methods associated with those structs.</p><p>One downside of using traits is that it only works for methods. We cannot specify fields on a trait. That’s why instead of directly specifying a trait field called id, we use a helper function get_id() to achieve the same.</p><h3>Conclusion</h3><p>This article is already getting too long. I have learned so much while writing and researching about the article. All 3 of these languages provide multiple ways to store a collection of union-type values of varying size. At the end of the day, it all boils down to making trade-offs.</p><p>I like the enum associated value implementation of Rust. It provides similar ergonomics to the TypeScript version while retaining all the benefits of a compiled strongly typed language. Swift in that regard needs more syntactic sugar to achieve the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=078a7c95afce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A tale of Rust ownership and multiple mutable borrows]]></title>
            <link>https://medium.com/@Faisalbin/a-tale-of-rust-ownership-and-multiple-mutable-borrows-2858375b92f4?source=rss-347760846b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/2858375b92f4</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[memory-safety]]></category>
            <category><![CDATA[borrow-checker]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Faisal Bin Ahmed]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 21:06:00 GMT</pubDate>
            <atom:updated>2024-04-23T14:34:26.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjuo66wk-zz40Oy0K6bVBg.png" /><figcaption>Trying out my own comic characters for this article</figcaption></figure><p>Rust borrow checker has a big rule.</p><p>At any given point, you can have 1 mutable reference <strong>or</strong> multiple immutable references.</p><p>While I was learning Rust, the rule seemed pretty straight forward to me. A value on memory can have one owner*, and the owner can lend the read / write access to that memory location (a reference) to other entities ( another variable / function etc.); they are called a borrower.</p><p>You can also <em>sell</em> the rights to the value completely. In that case, the ownership has said to be moved. Let’s look at one example.</p><pre>let a = vec![1, 2, 3]; // variable a is the owner of the vector<br>let b = a; // variable b is now the owner of the vector<br><br>// variable a is no longer the owner of the vector and is invalidated</pre><p>In the above case, we transfer the ownership to b completely. Let’s say we don’t wanna transfer the ownership or clone a new vector while re-assigning. We can use a reference.</p><pre>let a = vec![1, 2, 3]; // variable a is the owner of the vector<br>let b = &amp;a; // variable b has an immutable reference to the vector<br>let c = &amp;a; // variable c also has an immutabe reference to the vector<br><br>// variable a is still the owner of the vector<br>// we can have as many immutable references as we want</pre><p>An immutable reference gives us the access to read it. From Rust’s perspective, this is memory safe. As the borrowers only have read access. Now if one of them also has the write access, the possiblity to reference something by a reader while it has been removed by the writer comes into play. This problem is known as a data race (lookup dangling pointers &amp; segfaults.) By disallowing this behavior, Rust eradicates a whole set of problem in your app. Not to mention, this all happens at compile time!</p><p>This is all sound and dandy but what if I want a mutable reference. Rust allows us to have only 1 at one point. If we have a mutable reference, we cannot have any other references, mutable or immutable.</p><pre>let mut a = vec![1, 2, 3]; // variable a is the owner, but this time<br>// we add the mut keyword to it specifying it&#39;s a mutable value<br>let b = &amp;mut a; // variable b has a mutable reference to the vector<br><br>let c = &amp;a; // &lt;---- ERROR: you cannot have an immutable borrow while there is<br>// a mutable borrow already</pre><p>I recently published a <a href="https://github.com/FaisalBinAhmed/MVGFahrinfo">Rust CLI tool</a> to display Munich public transport departures in your terminal.</p><p><a href="https://github.com/FaisalBinAhmed/MVGFahrinfo">GitHub - FaisalBinAhmed/MVGFahrinfo: Get up-to-date departure times for Munich public transport in your terminal.</a></p><p>The main function of the app looks like this:</p><pre>let mut app = App::new().await; // app is the owner of this App struct&#39;s instance<br><br>    while !app.should_quit {<br>        if app.should_redraw {<br>            tui.draw(&amp;mut app)?; // mutable borrow occurs<br>            app.should_redraw = false; // mutation occurs<br>        }<br><br>        match tui.events.next().await? {<br>            Event::Tick =&gt; {}<br>            Event::Key(key_event) =&gt; update(&amp;mut app, key_event).await, // another mutable borrow occurs<br>        };<br>    }</pre><p>This code may look confusing to many Rust beginners. So far we have been touting about how we can only have one mutable reference to a value. But from the code above, it looks like we are giving away mutable references like candies. We gave mutable references to the tui.draw() method, the update() method, while at the same time mutating the value in the block itself.</p><p>I also faced similar confusion while reading others’ code in the beginning. That’s why I decided to write this post.</p><p>Ok, why is Rust allowing multiple mutable reference in the same block scope?!</p><p>if we look closely, it will become clear to us. We are not actually breaking the borrow checker’s rule.</p><p>The main thing to understand here is scope. While it’s true, we gave multiple mutable references in the same block, the borrowers did not have the mutable rights <em>at the same time</em>.</p><p>When we gave tui.draw() method the first mutable reference, it did some work on it, perhaps read some fields from the struct instance, maybe even mutated some fields. But on the next line, <strong>it goes out of scope</strong>. As soon as the method is done executing, its <em>lifetime</em> has come to an end and <strong>we no longer have a mutable reference to that instance</strong>. That’s why in the next line we could just mutate the field `should_redraw` without Rust compiler complaining. The same happens when we give another mutable reference to the update() method. It is not <strong>another</strong> mutable reference. it is <strong>the only</strong> mutable reference at that point.</p><pre>struct App {<br>    should_quit: bool,<br>    nums: Vec&lt;i32&gt;<br>}<br><br>fn main(){<br>    let mut app = App{<br>        should_quit: false,<br>        nums: vec![1, 2, 3]<br>    };<br><br>    while !app.should_quit{<br>        print_nums(&amp;mut app); // 1st mutable reference<br>        // print_nums goes out of scope here, with it the 1st mutable reference<br>        app.should_quit = true;<br>        // at this point, app variable is the owner and there&#39;s no references<br>        print_nums2(&amp;mut app); // 2nd mutable reference<br>        // no references exist at this point<br>    }    <br>}<br><br>fn print_nums(app: &amp;mut App){<br>    println!(&quot;{:?}&quot;, app.nums);<br>    app.nums.push(4);<br>}<br>fn print_nums2(app: &amp;mut App){<br>    println!(&quot;{:?}&quot;, app.nums);<br>    app.nums.push(4);<br>}<br><br>// program outputs:<br>// [1, 2, 3]<br>// [1, 2, 3, 4]</pre><p>I have made the above code to illustrate the explanation better.</p><p>While at first glance, it might look like we are allowing multiple references to a value, in reality, we are not. It all has to do with scope and lifetime.</p><p>I hope this post has made your Rust understanding just a bit better!</p><p>*we can have multiple owners with smart pointers but that’s a topic for another day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2858375b92f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All the wrong ways to persist in-app purchase status in your macOS app]]></title>
            <link>https://medium.com/@Faisalbin/all-the-wrong-ways-to-persist-in-app-purchase-status-in-your-macos-app-ce6eb9bcb0c3?source=rss-347760846b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce6eb9bcb0c3</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[in-app-purchase]]></category>
            <category><![CDATA[storekit]]></category>
            <dc:creator><![CDATA[Faisal Bin Ahmed]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 16:51:31 GMT</pubDate>
            <atom:updated>2023-05-14T14:16:03.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0jEKNskty3OVTxwppn5nQ.png" /></figure><p>The fastest way to deploy a premium feature in your app is to create two separate binaries for it: A free version, and a paid one with all the bells and whistles. Of course, this is not a great model for the long run as you have to support two separate apps. But if you don’t want to deal with all the in-app purchase headaches, this is surely one way to go. Just ask the third-party Reddit app developers on the Play Store.</p><p>As I was developing my latest MacOS app: <a href="https://apps.apple.com/us/app/cliptonite-clipboard-manager/id6446803122">Cliptonite</a>, I wanted to use a different revenue model for it other than the easiest solution in terms of developer experience. My previous app Keytrails was a paid-only app. As a result, the app hasn’t attracted as many users as I hoped. To my credit, at the time, I didn’t know how to implement in-app purchases, and I wanted to ship fast.</p><p>After dealing with Apple’s Storekit 2 vs Original in-app Purchase APIs (more on that later), I finally had a working solution to handle in-app purchases in my app. But then came the next big question: <strong>how do you persist the validity of the purchase throughout the lifetime of your app install?</strong> The answer is more tricky than I thought. So tricky, I decided to write this article.</p><p>It’s worth mentioning now, the solution is much straight forward in the latest StoreKit 2 API. Since my target macOS version was 11, I couldn’t use the latest APIs. But my findings should still apply to people on the bleeding edge.</p><p>There are a couple of ways to deal with persisting purchase validity inside your app. I will go through them in the order I tested them.</p><ol><li><strong>UserDefaults</strong><br>This is the easiest and most obvious of the bunch. So I decided to store whether the pro version was purchased inside the UserDefaults first. What could go wrong, right?</li></ol><pre>let K_USER_HAS_PURCHASED_PRO = &quot;userHasPurchasedPro&quot;;<br><br>class SettingsObject: ObservableObject {<br><br>@Published var userHasPurchasedPro = false;<br>let defaults = UserDefaults.standard;<br><br>init(){<br>self.userHasPurchasedPro = defaults.bool(forKey: K_USER_HAS_PURCHASED_PRO)<br>}<br><br>// After successful purchase/restore confirmation from StoreKit, this method is called<br>func makePro(){<br>  self.userHasPurchasedPro = true;<br>  defaults.set(true, forKey: K_USER_HAS_PURCHASED_PRO)<br>}<br><br>}</pre><p>As soon as my user buys/restores the pro version, I update the state of my app and unlock all the features. On subsequent launches, the app looks for a specific value in the UserDefaults and enables the pro flag on start.</p><p>There are a few caveats with this approach — let’s see how this value is stored on the user&#39;s device:</p><p>On macOS, these user values are stored in a .plist file. As they are “UserDefaults,” this file is accessible by the user. Even if your app is sandboxed and distributed through AppStore. This file is located at:</p><p>/Users/<strong>USER_NAME</strong>/Library/Containers/<strong>APP.BUNDLE.ID</strong>/Data/Library/Preferences</p><p>Just go there from Finder, and you can see all the UserDefaults values in their full glory.</p><p>My naive self thought: this file is definitely read-only and only my app has the write access. I was wrong. You can edit the values with any text editor that can read binary encoded plist contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7m4bTLqzgVbcWncRQwi70Q.png" /><figcaption>Figure: plist file of an actual app I downloaded from AppStore</figcaption></figure><p>And just like that, any user can write a &lt;true/&gt; value to the specific key, and unlock the pro version, without paying any dime.</p><p>As soon as I restarted my app to unlock the Pro feature, I was surprised, it was still showing the free version, what happened? The value I stored there is still showing true, could this be a bug in my logic?</p><p>As it turns out Apple has one last guard to prevent manual editing of these plist files: cfprefsd</p><p>cfprefsd is a background process that stores all the UserDefaults value across the system in memory. So even if someone manually edits the file, the app might still fetch the cached value from this process instead. As soon as your app exits, cfprefsd restores the original content of the file, maintaining its integrity.</p><p>That all sounds good until you open Activity Monitor or terminal to kill all of the cfprefsd processes in your system. Who’s going to protect the file now?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEUQvC1nFtzBCb7IR5MwqA.png" /><figcaption>Figure: quit all the processes and then edit the plist file.</figcaption></figure><p>To macOS’ credit, it does restart the process as soon as it detects this, however, this leaves just enough time window to save the new changes to the plist file.</p><p>Et Voila! I have successfully “purchased” the pro version of the app without spending anything.</p><p>Now even if I restart my system, neither the app nor cfprefsd has any idea that the file has been tampered with. Leaving me with the pro version forever.</p><p><strong>Prerequisite</strong>: the user should know the exact name of the key to toggle the value TRUE. This is easy if someone who already purchased the app decides to share the information with the world.</p><blockquote>Disclaimer: Please do not use this method for piracy. Developers like me spend a lot of time on our app. If you really can’t afford the app, sometimes a simple email to the devs can help.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LE5AxPPT_SiDNQjrUHozRg.png" /><figcaption>Figure: from Apple’s developer <a href="https://developer.apple.com/documentation/storekit/in-app_purchase/original_api_for_in-app_purchase/persisting_a_purchase">website</a></figcaption></figure><p>This is BS, I thought to myself. If anyone and their mother can write to this file, Apple should NOT advertise this as a solution on their website. We need something more robust and less accessible.</p><p>2. <strong>Keychain</strong></p><p>The next step in your arsenal is storing the flag inside Keychain. It <em>sounds</em> so secure! So I decided to do that instead.</p><p>Veteran iOS/macOS developers know dealing with Keychain used to be a bit of a pain. Fortunately, there are many wrappers with simple Swift APIs. I decided to go with auth0’s <a href="https://github.com/auth0/SimpleKeychain">SimpleKeychain</a>.</p><p>I updated my SettingsObject class by replacing UserDefaults related code with Keychain-specific code. The updated class looks like this:</p><pre>let K_USER_HAS_PURCHASED_PRO = &quot;userHasPurchasedPro&quot;;<br><br>class SettingsObject: ObservableObject {<br><br>@Published var userHasPurchasedPro = false;<br>let simpleKeychain = SimpleKeychain();<br><br>init(){<br>    do {<br>        self.userHasPurchasedPro = try simpleKeychain.hasItem(forKey: K_USER_HAS_PURCHASED_PRO)<br>      } catch _ as SimpleKeychainError {<br>      } catch {<br>      }<br>}<br><br>func makePro(){<br>        do {<br>            self.userHasPurchasedPro = true;<br>            try simpleKeychain.set(&quot;true&quot;, forKey: K_USER_HAS_PURCHASED_PRO)<br>        } catch _ as SimpleKeychainError {<br>        } catch {<br>        }<br>    }</pre><p>Now no malicious app can tamper with this value. Anything inside Keychain is protected by password access. Only the user can access this value.</p><p><em>Only the user can access this value.</em></p><p>Let’s see how this is stored in Keychain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbJyL-zrQxE-7Wm-8GQKRA.png" /><figcaption>Figure: editing the value inside Keychain</figcaption></figure><p>If you search for the bundle id (or just the app name), you can see, Cliptonite has stored an application password inside your Keychain, and just like UserDefaults, users can modify this value from false to true to unlock the full version.</p><p>So we have solved one problem with Keychain: we eradicated the possibility of any third-party tools overwriting our data. However, if a user wants, they can still unlock the app for free. Not good.</p><p>But Faisal, <em>you ask</em>, you are storing the true value only when the user has purchased the good, surely they can’t edit a nonexistent item in Keychain? You’d be right and wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S89jp0FSG1KL-QiHUK8EWg.png" /><figcaption>Figure: creating a new keychain item</figcaption></figure><p>Turns out Keychain lets you create arbitrary application passwords just like the one shown above. You just need to know the Account Name, in our case: “userHasPurchasedPro”</p><p>Can we improve this solution?</p><p>3. <strong>Combining Keychain with UserDefaults</strong></p><p>What if the users don’t know the exact string? What if we store a random string for each user?</p><p>This would solve our problem of users creating a new Keychain item. On every app launch, we generate a random string (let’s call it salt), and when the user purchases the item from AppStore, we store this salt in UserDefaults and create a new Keychain item with this salt as the key.</p><p>Users can’t know the exact key until after they purchase the app, and they can’t share it on the internet as it’s unique for each user. Let’s look at the updated code.</p><pre>let K_SALT_ID=&quot;saltID&quot;<br><br>class SettingsObject: ObservableObject {<br>    <br>    @Published var userHasPurchasedPro = false;<br>    let simpleKeychain = SimpleKeychain();<br>    let defaults = UserDefaults.standard<br>    <br>    init() {<br>  <br>        if let saltID = defaults.string(forKey: K_SALT_ID) {<br>            // salt exists in UserDefsults<br>            // means user has purchased it<br>            do {<br>                //only make the app Pro, when both checks are true<br>                self.userHasPurchasedPro = try simpleKeychain.hasItem(forKey: saltID)<br>            } catch _ as SimpleKeychainError {<br>            } catch {<br>            }<br>        }<br>        <br>    }<br>    <br>    func makePro(){<br>        self.userHasPurchasedPro = true;<br>        let salt = UUID().uuidString; //using random UUID string as our salt<br>        do {<br>            defaults.set(salt, K_SALT_ID)<br>            try simpleKeychain.set(&quot;true&quot;, forKey: salt)<br>        } catch _ as SimpleKeychainError {<br>        } catch {<br>        }<br>    }<br>  <br>}</pre><p>I was quite happy when I came up with this idea. For a solid few minutes, I thought this was foolproof. I created an ingenious solution!</p><p>Soon my bubble burst and I realized I solved nothing. Can you spot the error in my logic?</p><p>Now users have to generate a random UUID string and write it both in the UserDefaults plist file and in the Keychain to unlock the Pro. This achieves nothing.</p><p>At this moment I was quite hopeless, Until this point, I was holding off on the idea of properly doing the groundwork behind in-app purchase verification. I thought I can achieve the same thing with just UserDefaults and/or Keychain. It was finally time to move on.</p><p>4. <strong>App Receipts</strong></p><p>After each successful transaction, App Store stores a <a href="https://developer.apple.com/documentation/appstorereceipts/validating_receipts_on_the_device">cryptographically signed receipt</a> of the user’s purchase history on the device. As long as you validate the authenticity of the receipt, and check for the proper transaction confirmation in the file, you’re good to go.</p><p>Fortunately, there is a really nice Swift-based library to do all that for you. It takes care of the validation and verification of specific transactions as well as the receipt. Shout out to <a href="https://github.com/tikhop/TPInAppReceipt">TPInAppReceipt</a>.</p><p>Now my SettingsObject class looks like this:</p><pre>class SettingsObject: ObservableObject {<br>    <br>    @Published var userHasPurchasedPro = false;<br>    <br>    init() {<br>  <br>        if let receipt = try? InAppReceipt.localReceipt(){<br>            if receipt.containsPurchase(ofProductIdentifier: PRODUCT_ID){ //your in-app purchase Product ID<br>                // user has indeed purchased this product<br>                self.userHasPurchasedPro = true<br>            }<br>        }     <br>    }<br>    <br>    func makePro(){<br>        self.userHasPurchasedPro = true;<br>    }<br>  <br>}</pre><p>With just a few lines of code, you can now properly verify the purchase status of your in-app purchase. Additionally, you should also add code to validate and refresh the receipt itself. Please refer to their GitHub for more API references.</p><p>This was a roller coaster ride for me. I am still a relatively new Swift/Appkit developer. For experienced developers, this might even sound silly. But after researching about it for days, and reading lots of articles and StackOverflow entries, I know I am not the only one on this boat.</p><p>I hope this was an educational read for you. I will be happy if this article helps developers who are still unsure about this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce6eb9bcb0c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yepo 737s Plus Review — A $200 Notebook in a MacBook Air Enclosure]]></title>
            <link>https://medium.com/@Faisalbin/yepo-737s-plus-review-a-200-notebook-in-a-macbook-air-enclosure-8dc2526b810b?source=rss-347760846b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dc2526b810b</guid>
            <category><![CDATA[laptop]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[macbook]]></category>
            <dc:creator><![CDATA[Faisal Bin Ahmed]]></dc:creator>
            <pubDate>Sun, 22 Oct 2017 18:31:14 GMT</pubDate>
            <atom:updated>2017-10-22T18:31:14.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNT0GnD9BKSxFALQS8MyoA.jpeg" /></figure><p>The general consensus about Windows laptops in the sub $200 range is, they are not as good as they should be. Most laptops in the price segment have mediocre screen, 2GB RAM, bulky design and terrible battery life. For a student who is looking for a cheap laptop, these simply won’t cut it. Hence, Chromebooks are becoming more and more popular with the students as they give much better battery life and the features most students look for in a laptop.</p><p>Yepo 737s Plus is one such Windows laptop that could give Chromebook a run for its money. It’s something I look for in a laptop of this price. It has a full HD display, 4GB of RAM, an eMMC SSD and above all, good battery life. For a full overview, here’s its spec sheet:</p><blockquote>Display: 13.3″, 1920 x 1080 pixels, TN panel</blockquote><blockquote>CPU: Intel Atom Cherry Trail, x5-Z8300, 2M cache, 1.84 GHz, quad core</blockquote><blockquote>Ram: 4GB DDR3L 1333Mhz</blockquote><blockquote>Storage: 128GB flash based eMMC with an SD slot</blockquote><blockquote>OS: Windows 10 Home preinstalled</blockquote><blockquote>Camera: 1.3MP</blockquote><blockquote>Battery: 8000mAh</blockquote><blockquote>Dimension: 336mm x 224mm x 10.5mm</blockquote><blockquote>Weight: 1.14 KG</blockquote><blockquote>I/O: 3.5mm headphone jack, SD slot, 2 USB 2.0, mini HDMI, DC</blockquote><p>Pretty solid for the price. If Yepo can provide a notebook of this spec for $200, why can’t the mainstream PC makers do so? Or is there a catch? Let’s dive into the individual component.</p><p><strong>Build and design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jVOQ7ccbN2f_a9weFGLyQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qIDukAHOG8i4seAqvMcDg.jpeg" /></figure><p>There’s no denying that this is a MacBook Air design. The color, illuminated logo, keyboard layout, spacious touchpad, I/O, everything resembles the small MacBook except for the build quality. The body is mostly a plastic construction with metal floor for the bottom chamber that helps with the cooling (more on that later). The plastic looks cheap, but the texture makes it a little cold to touch. Although it’s nowhere close to a metal feel.</p><p>I tried to open the lid with one hand, but to no avail. Not sure what I was expecting there. Once the lid is open, it stays quite stable. There’s a little flex to the basement area, as to be expected from a laptop this cheap. They didn’t try to tinker with the standard I/O layout of the MacBook Air. The DC input is no MagSafe but it gets the job done.</p><p><strong>Display</strong></p><p>The display is one of the reasons why the notebook picked up my attention. It’s so rare to see a decent panel on budget laptops these days, it’s sad. The 1080p panel makes it stand out in the sea of 768p laptops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dtJjp_7gFWCqTpUaLsxNug.jpeg" /><figcaption>Them pixels</figcaption></figure><p>Since it’s a TN panel, don’t expect the color production or viewing angle of IPS. But TN has its perks. It’s cheap and can get very fast. The panel in this one is certainly one of the better ones I’ve seen in the price range. The Blacks can go quite deep, but the Whites and the Greys struggle to keep up with it. The colors get distorted when you’re viewing from a side.</p><p>The display gets pretty dim with brightness set to 0%, but I still find it a little brighter for my taste. On the bright side, its backlight can emit sufficient light for daytime viewing, which I would have appreciated more had it had a non reflective coating on the display.</p><p><strong>Keyboard and touchpad</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*0FM8D6dTPcZ_bkpHNlamKw.jpeg" /><figcaption>The Keyboard has good travel</figcaption></figure><p>My biggest gripe about the device is the touchpad. Only good thing about it is it’s big. It doesn’t register my touch as well as I expect it to. Many times it would just ignore my soft touches, so you have to be really deliberate when navigating the cursor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*rrOjOkoDDceCFIFE4y-Zjg.jpeg" /></figure><p>It supports the popular Windows 10 gestures like two finger scrolling, 4 finger swipe up to reveal task switcher etc. I see no way to change these gestures though. There are no third party(or is it first party?) driver for this.</p><p>The keyboard on the other hand makes up for the poor touchpad. The keys are laid out according to the US layout. For a membrane keyboard, it provides a great feedback upon typing. It’s quite springy and so the keys bounce back very quickly. A mechanical keyboard user like me had no problem typing on it.</p><p><strong>Software</strong></p><p>The laptop comes with Windows 10 Home edition installed. When I opened it I had to change the Language from Mandarin to English. So look out for that; if you are new to Windows 10, you might have a hard time configuring.</p><p>Surprisingly, it had no bloatware. A huge plus in my book. It also didn’t have any special software to configure device specific settings. The hardware is so generic, the OEM didn’t bother with making any. Windows provides all of the default drivers.</p><p><strong>Performance</strong></p><p>The performance is a hit or miss depending on your use case. If you’re only going to use the browser, play some videos, write documents etc, the Atom chip and the 4GB RAM will be sufficient. Light gaming like playing Asphalt 8 or similar titles from the Windows Store is achievable. But I did see some stutters playing Riptide GP2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*t7V9QX0Byrlkq4cipIsT3A.jpeg" /><figcaption>CrystalDiskMark benchmark</figcaption></figure><p>Here’s the benchmark of the flash based SSD. It’s fairly normal for a flash storage. The sequential r/w speeds are on par with most 2.5″ drives. But random r/w is where it beats normal HDDs, as expected. The added data bandwidth certainly helps in many cases. The OS starts fast. UWP applications response quickly. The SSD also helps making the laptop incredibly thin and light.</p><p>Thermal dissipation is done via the metal basement alone. Only thing touching the SoC and the metal is a thermal pad. I wouldn’t say it’s insufficient, but it does get a little warmer after a while, especially in the lower right corner. Fortunately, I have not experienced any throttling.</p><p><strong>Battery life</strong></p><p>I’ve been using the laptop for 3 weeks now. To make a comment about its endurance, first I have to state what type of user I am. I do most of my heavy work on desktop. The laptop is used for browsing/streaming while I’m on bed. Also when I’m outside, taking class notes, emailing etc. The first few days of any gadget testing tells a misleading story about its endurance. It needs a few power cycles to adjust. After one week, the notebook settled on a stable backup time. It gives me 5–6 hours of play time after a full charge. Again this might vary depending on your use case. For me though, I would call it impressive for the price.</p><p>One thing I must mention, the AC adapter provided with the laptop outputs current very slowly. It takes 3–3.5 hours to charge this thing. I had a matching spare AC adapter lying around, which charges it an hour quicker.</p><p><strong>Conclusion</strong></p><p>This is my first time using a Chinese no name notebook. I’m surprised to say that it has chanced my perspective about this breed of laptops. The smartphone market was flooded with Chinese phones, and it changed the industry for good. The build quality is not on par with branded laptops, but for $200 (or less in some places), the value it gives is unprecedented for PC market. I’m happy that it exists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dc2526b810b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>