<?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 Ahmad Fayyas on Medium]]></title>
        <description><![CDATA[Stories by Ahmad Fayyas on Medium]]></description>
        <link>https://medium.com/@ahmadfayyas?source=rss-c523b085d034------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FCJYWaga44RWjKFT7Kif6Q.jpeg</url>
            <title>Stories by Ahmad Fayyas on Medium</title>
            <link>https://medium.com/@ahmadfayyas?source=rss-c523b085d034------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:49:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmadfayyas/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[Flutter Space Tour]]></title>
            <link>https://medium.com/@ahmadfayyas/flutter-space-tour-de0a0b174761?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0a0b174761</guid>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Fri, 31 May 2024 11:40:39 GMT</pubDate>
            <atom:updated>2024-05-31T11:40:39.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITr9QC88ryV0JjkLscEpDA.jpeg" /><figcaption><em>Space</em> 🧑‍🚀🛰, or Space 📐📏?!</figcaption></figure><p><em>This article will take you on a tour of some of the key techniques for adding spaces when building a UI in Flutter. Buckle up and enjoy!</em></p><p>In Flutter, spaces are widgets inserted between other widgets or can be seen as paddings, which provide surrounding space around other widgets.</p><p>Essentially, this combination occurs inside a <em>layout widget.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*wrpJ__Pk9P5UTnW5wKwxww.png" /></figure><h3>⭐ Layout widget</h3><blockquote>Arrange other widgets columns, rows, grids, and many other layouts.</blockquote><blockquote><a href="https://docs.flutter.dev/ui/widgets/layout">Documentation</a>.</blockquote><p>A layout widget is specifically designed to manage the arrangement and positioning of other widgets within the user interface. These widgets are essential for structuring visual elements and controlling the display of UI components.</p><p><strong>The first technique</strong> is to utilize the built-in options provided by layout widgets without <em>explicitly</em> adding space widgets.</p><p>For example, let’s take a look at the <a href="https://api.flutter.dev/flutter/widgets/Row-class.html">Row</a> widget:</p><pre>Row(<br>  children: [<br>    Container(color: Colors.red, width: 100, height: 100),<br>    Container(color: Colors.blue, width: 50, height: 50),<br>    Container(color: Colors.green, width: 70, height: 70),<br>   ],<br>)</pre><p>By default, without setting axis alignment, the output is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*001NFgho6fqBq-nQJO1_Nw.png" /></figure><p>By leveraging the Axis Alignments, we can add space between its children:</p><pre>Row(<br>  mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>  crossAxisAlignment: CrossAxisAlignment.end,<br>  children: [<br>    Container(color: Colors.red, width: 100, height: 100),<br>    Container(color: Colors.blue, width: 50, height: 50),<br>    Container(color: Colors.green, width: 70, height: 70),<br>   ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*yOeM-w0fL8B7SJxsnFO90w.png" /></figure><p>There are multiple <a href="https://api.flutter.dev/flutter/rendering/MainAxisAlignment.html">mainAxisAlignment</a> and <a href="https://api.flutter.dev/flutter/rendering/CrossAxisAlignment.html">crossAxisAlignment</a> values to add spaces between the inner widgets (children) of the row, choose whatever fits your design!</p><p>Another example is the <a href="https://api.flutter.dev/flutter/widgets/Wrap-class.html">Wrap</a> widget:</p><pre>Wrap(<br>  children: [<br>    Container(color: Colors.red, width: 100, height: 100),<br>    Container(color: Colors.blue, width: 50, height: 50),<br>    Container(color: Colors.green, width: 70, height: 70),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*NwS2hO6ACPH5d1102F6cUQ.png" /></figure><p>Adding spaces:</p><pre>Wrap(<br>  alignment: WrapAlignment.end,<br>  crossAxisAlignment: WrapCrossAlignment.end,<br>  spacing: 100,<br>  runSpacing: 20,<br>  children: [<br>    Container(color: Colors.red, width: 100, height: 100),<br>    Container(color: Colors.blue, width: 50, height: 50),<br>    Container(color: Colors.green, width: 70, height: 70),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*OP6FS2ScRUHy1__bTruurg.png" /></figure><p>Wrap has spacing property to set the vertical space, and runSpacing to set the horizontal space between its children in addition to the axis alignments.</p><p>Combining layout widgets to utilize the available options for building the UI, including setting appropriate spaces, is possible.</p><p>Here is a layout widgets combination, as a <a href="https://api.flutter.dev/flutter/widgets/Column-class.html">Column</a> contains multiple Rows:</p><pre>Column(<br>  mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>  children: [<br>    Row(<br>      children: [<br>        Container(color: Colors.amber, width: 100, height: 100),<br>        Container(color: Colors.amber, width: 100, height: 100),<br>        Container(color: Colors.amber, width: 100, height: 100),<br>      ],<br>    ),<br>    Row(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        Container(color: Colors.amber, width: 100, height: 100),<br>        Container(color: Colors.amber, width: 100, height: 100),<br>        Container(color: Colors.amber, width: 100, height: 100),<br>      ],<br>    ),<br>    Row(<br>      mainAxisAlignment: MainAxisAlignment.end,<br>      children: [<br>        Container(color: Colors.amber, width: 100, height: 100),<br>        Container(color: Colors.amber, width: 100, height: 100),<br>        Container(color: Colors.amber, width: 100, height: 100),<br>       ],<br>    ),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*7iE9MIcJiSFjtb5PDKMY5Q.png" /></figure><p>Most layout widgets offer various properties to set the spacing for their children. Some, like the Wrap widget, include additional parameters (such as spacing and runSpacing) to provide more control over the spacing between their children.</p><p><strong>However</strong>, relying on the layout widgets&#39; default spacing options is unreliable for adding <em>custom-valued</em> spaces.</p><h3>⭐ Padding</h3><blockquote>A widget that insets its child by the given padding.</blockquote><blockquote><a href="https://api.flutter.dev/flutter/widgets/Padding-class.html">Documentation</a>.</blockquote><p>Padding can be seen as space added around the edges of its child widget, offering visual separation between the child widget and its surrounding elements.</p><p><strong>The second technique</strong> is to wrap the widget with padding, setting the space around each side.</p><p>Here is an example of adding a custom-valued space:</p><pre>Row(<br>  children: [<br>    Padding(<br>      padding: const EdgeInsets.symmetric(horizontal: 20),<br>      child: Container(color: Colors.red, width: 100, height: 100),<br>    ),<br>    Container(color: Colors.green, width: 100, height: 100),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*0vPzALjnmVHQhoRRsDw29g.png" /></figure><p>The red container is wrapped with padding that adds horizontal spaces symmetrically (on the right and the left sides), as values of 20.</p><p>Another example:</p><pre>Column(<br>  children: [<br>    Padding(<br>      padding: const EdgeInsets.only(bottom: 20),<br>      child: Container(color: Colors.red, width: 100, height: 100),<br>    ),<br>    Container(color: Colors.green, width: 100, height: 100),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*z3Gc2JM9xtw_FZTOrq5o4w.png" /></figure><p>The red container is wrapped with padding that adds space only below it, as a value of 20.</p><p>Surrounding a widget with space:</p><pre>Container(<br>  color: Colors.green,<br>  width: 150,<br>  height: 150,<br>  child: Padding(<br>    padding: const EdgeInsets.fromLTRB(<br>      40.0,<br>      10.0,<br>      15.0,<br>      50.0,<br>    ),<br>    child: Container(color: Colors.red),<br>  ),<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*gPJbsKdc9Ut8QAZm8Um0pA.png" /></figure><p>The red container is the inner container of the green one, wrapped with padding that adds space around it with different custom values. In my opinion, this is the most preferable use of padding. It excels at adding surrounding space for the padding’s child, especially when different values are applied to each side.</p><h4><strong>💡 Tip:</strong></h4><p>You can directly set the padding of the Container for its child without wrapping the child in a Padding widget. In other words, you can alternatively wrap your widget with a Container and set its padding, eliminating the need for a separate Padding widget. For Example:</p><pre>Container(<br>  padding: const EdgeInsets.fromLTRB(<br>    40.0,<br>    10.0,<br>    15.0,<br>    50.0,<br>  ),<br>  color: Colors.green,<br>  width: 150,<br>  height: 150,<br>  child: Container(color: Colors.red),<br>)</pre><p>Outputs an identical result to the previous example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*gPJbsKdc9Ut8QAZm8Um0pA.png" /></figure><p><strong>So, when to use a </strong><strong>Container with </strong><strong>padding instead of a </strong><strong>Padding widget?</strong></p><p>Here is a guideline that I typically adhere to when making this decision:</p><ul><li>Begin by using the Padding widget initially. In most cases, it’s the preferred method for setting the padding of a particular widget, rather than wrapping it with a Container that has a padding set, as it indicates that the padding is added explicitly for that purpose.</li><li>If there’s a need to wrap an existing Container’s child with Padding, it’s advised not to do so. Instead, set the padding directly of the Container. Interestingly, the question in such a case would be:</li></ul><p><strong>What is the primary purpose of the container? Is it solely for setting the padding of its child?</strong></p><p>“Yes”: Follow the first point; “No”: Consider the second point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*bThX13YJtm_rUOu_09QZeA.png" /></figure><p>Padding allows adding space around its child widget by controlling the distance between the child and parent widget.</p><p><strong>However</strong>, based on my personal preference, I don’t always prefer to use the Padding widget when adding space to a single side. I prefer avoiding wrapping a widget with another one to add a single space, even for symmetric spaces with different values. Instead, I would follow a different technique, using a separate widget to add space. This approach helps avoid unnecessary widget nesting, which can result in unclear/complex widget tree hierarchy.</p><h3>⭐ SizedBox</h3><blockquote>A box with a specified size.</blockquote><blockquote><a href="https://api.flutter.dev/flutter/widgets/SizedBox-class.html">Documentation.</a></blockquote><p>Sized Box is an explicit width/height widget. Although it can hold a child widget (to control its size), it&#39;s practical for adding space.</p><p><strong>The third technique </strong>is to add a sized box between the widgets.</p><p>Example of adding H<strong>orizontal</strong> space:</p><pre>Row(<br>  children: [<br>    Container(color: Colors.red, width: 100, height: 100),<br>    const SizedBox(width: 20),<br>    Container(color: Colors.green, width: 100, height: 100),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*0vPzALjnmVHQhoRRsDw29g.png" /></figure><p>The space (sized box) is between the red and green containers, with a value of 20.</p><p><strong>Vertical</strong> space:</p><pre>Column(<br>  children: [<br>    Container(color: Colors.red, width: 100, height: 100),<br>    const SizedBox(height: 20),<br>    Container(color: Colors.green, width: 100, height: 100),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*z3Gc2JM9xtw_FZTOrq5o4w.png" /></figure><p>Similarly, the space (sized box) is between the red and green containers, with a value of 20.</p><p>I’m confident that your memory 🧠 is sharp enough to recognize that these examples produce the same output as the previous ones with padding!</p><p><strong>What about the widget tree?</strong></p><p>Here is what I meant by previously mentioning that I prefer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*IPGn_xlnwCl2iN0CZrRwrA.png" /><figcaption>Adding space using SizedBox</figcaption></figure><p>instead of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*dx863kJIQOFHl7IAUfFvCA.png" /><figcaption>Adding space using Padding</figcaption></figure><blockquote><em>It’s not an absolute rule, ultimately, both approaches will yield the same output. </em>You might even discover that using padding aligns better with the “Separation of Concerns” principle, as it separates the padding logic from the child widget, more maintainable, flexible, or even readable! There’s nothing wrong with using it for adding a single space. Just remember, it’s all about personal preference.</blockquote><h4>SizedBox as a space — Let’s make it “cooler” 😎</h4><p>Since we aim to use the SizedBox as a space, let’s make our own wrappers!</p><pre>class XSpace extends StatelessWidget {<br>  final double x;<br><br>  const XSpace(<br>    this.x, {<br>    Key? key,<br>  }) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(width: x);<br>  }<br>}<br><br>class YSpace extends StatelessWidget {<br>  final double y;<br><br>  const YSpace(<br>    this.y, {<br>    Key? key,<br>  }) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(height: y);<br>  }<br>}</pre><p>These are simple classes that wrap around SizedBox to explicitly represent widgets for y and x spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0gV8gwPrD3y4oNgM_K5uXg.gif" /></figure><p>Now, we have custom spaces widgets, that can be used (instead of SizedBox directly) as:</p><pre>// Horizontal Space<br>Row(<br>    children: [<br>        Container(color: Colors.red, width: 100, height: 100),<br>        const XSpace(20),<br>        Container(color: Colors.green, width: 100, height: 100),<br>       ],<br>)<br><br>// Vertical Space<br>Column(<br>    children: [<br>        Container(color: Colors.red, width: 100, height: 100),<br>        const YSpace(20),<br>        Container(color: Colors.green, width: 100, height: 100),<br>    ],<br>)</pre><p>to get the same outputs correspondingly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*0vPzALjnmVHQhoRRsDw29g.png" /><figcaption>Horizontal Space (XSpace)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*z3Gc2JM9xtw_FZTOrq5o4w.png" /><figcaption>Vertical Space (YSpace)</figcaption></figure><p>In addition to controlling widget size, one of the common usages of the Sized Box is creating spaces between the widgets. Additionally, as a semantic clarity improvement, we’ve created XSpace and YSpace for more explicitly and readability.</p><p>Creating wrappers can be a smart approach. It inspires making them more intelligent ✨, by recognizing the direction of the space — whether vertical or horizontal — based on its parent widget (like a Row or a Column), dynamically adapts with small amounts of space to avoid overflow, or perhaps even stays reliable with custom scrolling actions (Hello, <a href="https://docs.flutter.dev/ui/layout/scrolling/slivers">Slivers</a>!). Oh boy! That’s a lot of work, but the possibilities are exciting…!</p><h3>⭐ Gap</h3><blockquote>Flutter widgets for easily adding gaps inside Flex widgets such as Columns and Rows or scrolling views.</blockquote><blockquote><a href="https://pub.dev/documentation/gap/latest/">Documentation.</a></blockquote><p>Gap makes it easier to manage spacing between widgets, reducing the need for complex margin or padding configurations on individual widgets. It’s adaptable to different screen sizes and orientations.</p><p><em>It seems it’s our wrapper’s “smarter” version, right?!</em></p><p><strong>The fourth technique </strong>is to add a gap between the widgets.</p><p><em>You’ll need to install it manually (</em><em>flutter pub add gap) since it’s an external package, and import it as</em>import ‘package:gap/gap.dart’; 😶</p><p>H<strong>orizontal</strong> space:</p><pre>Row(<br>    children: [<br>        Container(color: Colors.red, width: 100, height: 100),<br>        const Gap(20),<br>        Container(color: Colors.green, width: 100, height: 100),<br>       ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*0vPzALjnmVHQhoRRsDw29g.png" /></figure><p><strong>Vertical</strong> space:</p><pre>Column(<br>    children: [<br>        Container(color: Colors.red, width: 100, height: 100),<br>        const Gap(20),<br>        Container(color: Colors.green, width: 100, height: 100),<br>    ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*z3Gc2JM9xtw_FZTOrq5o4w.png" /></figure><p>Now, there is no need to worry about the direction, Gap will take care of it (RIP XSpace and YSpace wrappers 😭)!</p><h4><strong>Furthermore, let’s fix the overflow!</strong></h4><p>Imagine a Row widget containing four distinct widgets. Our goal is to introduce a space in the middle, specifically after the second widget, with a value of 100.</p><p>Here is what we can do:</p><pre>Row(<br>  mainAxisAlignment: MainAxisAlignment.center,<br>  children: [<br>    Container(color: Colors.red, width: 75, height: 75),<br>    Container(color: Colors.green, width: 75, height: 75),<br>    const Gap(100),<br>    Container(color: Colors.blue, width: 75, height: 75),<br>    Container(color: Colors.amber, width: 75, height: 75),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eA0qopWmmv_kTZeZZzO4Gw.png" /></figure><p>So far so good! The Row’s mainAxisAlignment is center, therefore there is some space on the sides (and let’s say it’s acceptable in our case). <strong>However, </strong>this is the output of a relatively large screen size (iPhone Pro Max).</p><p>Let’s check it on a smaller screen, shall we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*u3msQmltfo1K02SattgUdg.png" /></figure><p>Ouch! we got an overflow!</p><p>Not enough horizontal space (screen width) to set the Row properly, not even when filling the side spaces… The value of the middle space of 100 is too much in this case, we need to make its <em>maximum</em> value as 100.</p><h4>💪 MaxGap to the rescue</h4><blockquote>The MaxGap widget will try to fill the available space in a Column or a Row with the specified size. If the available space is lesser than the specified size, the MaxGap widget will only take the available space.</blockquote><p>Let’s replace the const Gap(100) with const MapGap(100):</p><pre>Row(<br>  mainAxisAlignment: MainAxisAlignment.center,<br>  children: [<br>    Container(color: Colors.red, width: 75, height: 75),<br>    Container(color: Colors.green, width: 75, height: 75),<br>    const MapGap(100),<br>    Container(color: Colors.blue, width: 75, height: 75),<br>    Container(color: Colors.amber, width: 75, height: 75),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*0G_cRDoeofzWOgBdAnaGuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*W0XFrGS6eU37YqNEVX22hQ.png" /></figure><p>Now, the maximum value of the space is 100. This means it will be 100 if there is enough space based on the screen width; Otherwise, it will shrink to avoid overflow.</p><h4>What about the custom scrolling actions?</h4><p>No worries, the SliverGap is here!</p><blockquote>A sliver that takes a fixed amount of space.</blockquote><p>Here is an example of adding a space between the SliverAppBar and the SliverList:</p><pre>CustomScrollView(<br>  slivers: [<br>    const SliverAppBar(<br>      expandedHeight: 100.0,<br>      floating: true,<br>      pinned: true,<br>      flexibleSpace: FlexibleSpaceBar(<br>        background: ColoredBox(<br>          color: Colors.blue,<br>        ),<br>      ),<br>    ),<br>    const SliverGap(100),<br>    SliverList(<br>      delegate: SliverChildBuilderDelegate(<br>        (context, index) =&gt; ListTile(<br>          leading: const Icon(<br>            Icons.star,<br>            color: Colors.amber,<br>          ),<br>          title: Text(&#39;List Item #$index&#39;),<br>        ),<br>        childCount: 20,<br>      ),<br>    ),<br>  ],<br>),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*CWRbTzGDNI8McUg1A6Q6HA.gif" /></figure><p>The space of 100 (const SliverGap(100)) is below the SliverAppBar .</p><h3>🍒 Cherry on top</h3><p>Although the main techniques in mind have been covered, it might be beneficial to briefly explore some other widgets that can be useful in specific situations.</p><h4><a href="https://api.flutter.dev/flutter/widgets/Center-class.html">Center</a></h4><p>Simply, it’s used to center its child widget within its parent. Example:</p><pre>Container(<br>  color: Colors.blue,<br>  width: 100,<br>  height: 100,<br>  child: Center(<br>    child: Container(<br>      color: Colors.amber,<br>      width: 60,<br>      height: 60,<br>    ),<br>  ),<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*8fSfNmxhrib1GlJCHKANLA.png" /></figure><p>The blue container has a <em>centered</em> amber container both horizontally and vertically.</p><p>The beauty of using the Center widget is that you don’t have to worry about specific values; It automatically centers its child for you.</p><h4><a href="https://api.flutter.dev/flutter/widgets/Spacer-class.html">Spacer</a></h4><p>It creates an adjustable, space between widgets in a <a href="https://api.flutter.dev/flutter/widgets/Flex-class.html">Flex</a> container, such as Row and Column. Example:</p><pre>// Horizontal<br>Container(<br>  color: Colors.blue,<br>  width: 200,<br>  height: 100,<br>  child: Row(<br>    children: [<br>      Container(<br>        color: Colors.red,<br>        width: 50,<br>        height: 100,<br>      ),<br>      const Spacer(),<br>      Container(<br>        color: Colors.green,<br>        width: 50,<br>        height: 100,<br>      ),<br>    ],<br>  ),<br>)<br><br>// Vertical<br>Container(<br>  color: Colors.blue,<br>  width: 100,<br>  height: 200,<br>  child: Column(<br>    children: [<br>      Container(<br>        color: Colors.red,<br>        width: 100,<br>        height: 50,<br>      ),<br>      const Spacer(),<br>      Container(<br>        color: Colors.green,<br>        width: 100,<br>        height: 50,<br>      ),<br>    ],<br>  ),<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*bGRG2SqSdMc3yRoMqUwZRQ.png" /><figcaption>Horizontal Spacer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*r-4jzPtSM2pAzNvsXfMhAA.png" /><figcaption>Vertical Spacer</figcaption></figure><p>The Spacer adds the maximum available space between the Flex containers children (red and blue containers) inside its parent widget (blue container).</p><p>Spacer takes up the remaining space along the main axis, helping to distribute space evenly or push widgets to the ends of the container.</p><h4><a href="https://api.flutter.dev/flutter/widgets/Align-class.html">Align</a></h4><p>Aligning widgets can be viewed as adding surrounding space in a specific manner. Align is used to align its child within itself according to a specified alignment. Here is an example demonstrating all predefined alignments:</p><pre>Wrap(<br>  spacing: 20,<br>  runSpacing: 20,<br>  children: [<br>    ContainerAlign(alignment: Alignment.topLeft),<br>    ContainerAlign(alignment: Alignment.topCenter),<br>    ContainerAlign(alignment: Alignment.topRight),<br>    ContainerAlign(alignment: Alignment.centerLeft),<br>    ContainerAlign(alignment: Alignment.center),<br>    ContainerAlign(alignment: Alignment.centerRight),<br>    ContainerAlign(alignment: Alignment.bottomLeft),<br>    ContainerAlign(alignment: Alignment.bottomCenter),<br>    ContainerAlign(alignment: Alignment.bottomRight),<br>  ],<br>)</pre><p>For demonstration purposes, the alignment widgets are placed within a Wrap. ContainerAlign is the widget that contains the Align widget:</p><pre>class ContainerAlign extends StatelessWidget {<br>  final AlignmentGeometry alignment;<br>  const ContainerAlign({super.key, required this.alignment});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      height: 100,<br>      width: 100,<br>      color: Colors.blue,<br>      child: Align(<br>        alignment: alignment,<br>        child: Container(<br>          height: 50,<br>          width: 50,<br>          color: Colors.amber,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*DAq3D3PaeFDz7bAvbSuLwA.png" /></figure><p>Additionally, you can create an alignment with custom values. Example:</p><pre>Wrap(<br>  spacing: 20,<br>  runSpacing: 20,<br>  children: [<br>    ContainerAlign(alignment: Alignment(-0.6, -0.6)),<br>    ContainerAlign(alignment: Alignment(0.6, -0.6)),<br>    ContainerAlign(alignment: Alignment(2, -2)),<br>    ContainerAlign(alignment: Alignment(-0.6, 0.6)),<br>    ContainerAlign(alignment: Alignment(0.6, 0.6)),<br>    ContainerAlign(alignment: Alignment(2, 2)),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*RtNrrqv8xqjqUuBGym6A1Q.png" /></figure><p>Note that the x and y values range from -1.0 to 1.0, with -1.0 representing the start (left or top) and 1.0 representing the end (right or bottom). Nevertheless, you are not restricted to values between -1.0 and 1.0; Setting values less than -1.0 or greater than 1.0 will position the child widget <em>outside</em> the parent’s boundaries, as demonstrated in the two rightmost containers.</p><h4>💡 Tip:</h4><p>You can set the Container’s child alignment directly <em>without</em> wrapping it with an Align widget. Again, your sharp memory 🧠 tells you that it’s similar to setting the Container’s child padding as a replacement for having a separate Padding widget… That’s true! Setting the Container’s alignment is a replacement for having a separate Alignment. For Example:</p><pre>Container(<br>  alignment: Alignment.topLeft,<br>  color: Colors.blue,<br>  height: 100,<br>  width: 100,<br>  child: Container(<br>    color: Colors.amber,<br>    height: 50,<br>    width: 50,<br>  ),<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*ysNOi9L2B9JeZDeHyJSURg.png" /></figure><p>The amber container is aligned as topLeft in its blue parent container.</p><p><em>To answer the question:</em></p><p><strong><em>“When to use a </em></strong><strong><em>Container with </em></strong><strong><em>alignment instead of </em></strong><strong><em>Align widget?”</em></strong></p><p><em>Just follow the same guideline of setting the Container padding VS adding a Padding widget, just replace “</em><em>Padding” with “</em><em>Align” </em>🙃</p><h4><a href="https://api.flutter.dev/flutter/widgets/Positioned-class.html">Positioned</a></h4><p>Positioned is used to position its child widget relative to its parent in a <a href="https://api.flutter.dev/flutter/widgets/Stack-class.html">Stack</a> widget. Example:</p><pre>Container(<br>  height: 300,<br>  width: 200,<br>  color: Colors.blue,<br>  child: const Stack(<br>    children: [<br>      Positioned(<br>        top: 30,<br>        left: 70,<br>        width: 100,<br>        height: 100,<br>        child: ColoredBox(color: Colors.amber),<br>      ),<br>      Positioned(<br>        bottom: 30,<br>        right: 70,<br>        width: 100,<br>        height: 100,<br>        child: ColoredBox(color: Colors.amber),<br>      ),<br>    ],<br>  ),<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*SdtY0C66sB_XNzavryZkeA.png" /></figure><p>The blue container is the stack parent, the stack contains two amber containers, which are wrapped in positioned widgets to set their size (width and height) and position (top, left, bottom, and right).</p><p><strong>Btw, is it possible to use Positioned without stack?</strong></p><p>No. The Positioned widget is specifically designed to work within a Stack widget.</p><p>Adding spaces is a fundamental requirement for building a UI. In Flutter, there are multiple techniques to accomplish this, and there is no single “best way” to achieve it. Throughout this article, you have explored some of the main techniques for adding spaces, and you’ll discover others out there! It’s up to you to decide which approach to follow.</p><p>Hope you enjoyed the tour 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0a0b174761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new in Dart 2.17]]></title>
            <link>https://medium.com/@ahmadfayyas/whats-new-in-dart-2-17-75b7ba045082?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/75b7ba045082</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[dartlang]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Fri, 13 May 2022 00:20:13 GMT</pubDate>
            <atom:updated>2022-05-13T08:53:42.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Dart Logo" src="https://cdn-images-1.medium.com/max/225/1*_fXuD_NH6tQjtvwZ_i4syA.png" /></figure><h4>Flutter 3.0 is out there!</h4><p>Google <a href="https://docs.flutter.dev/development/tools/sdk/releases">released Flutter SDK 3.0</a>! No doubt there is a lot of excitement for seeing what’s new there, how it will make the development processes to be smoother, what are the performance improvements, how to support multiple cross-platforms easily with a single source code, what are the new widgets, and more.</p><h4>And… What about Dart?</h4><p>A newer Dart version 2.17 comes with Flutter 3.0. It seems there are some of the added “cool” features and enhancements to Dart as well, let’s take a look!</p><h4>But why bother?</h4><blockquote>My current Dart knowledge is enough to let me do the job.</blockquote><p><em>Are you one of us? What a legend </em>🤖.</p><p>For some reason, the part of the “programming language” itself is getting skipped a lot. However, It’s also important to know what’s new in the language used in the Flutter framework. It’s like any language, the more vocabulary we know the more we are able to communicate.</p><p>Ideally, we try not to miss knowing some of the “cool” language features that could make our life easier by “doing things” faster as well as writing more robust code. It also helps avoid the:</p><blockquote>Oh! So… I’m able to achieve it in a couple of lines while I’m writing a whole bunch of things. Well, <em>💩.</em></blockquote><p><strong><em>Plus, </em></strong><em>Dart sounds like a friendly programming language, why not have a better relationship with it </em>💙<em>?!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*ST8Akm9oMEg7ELwCfLUgGg.gif" /><figcaption>Dart Reaction</figcaption></figure><h3>So, What’s new in Dart 2.17?</h3><h4>⭐ <a href="https://github.com/dart-lang/language/blob/d16704ae6c9a5fd8f30b7ba9d33a5ab650c7447d/accepted/future-releases/enhanced-enums/feature-specification.md"><strong>Enumeration enchantments</strong></a><strong> </strong>⭐</h4><p>If you are familiar with any programming language with “powerful” enums, you are already aware of its sweetness. Dart enums have the same sweet taste now 🍭!</p><p><strong>Examples:</strong></p><p><em>Since there are many things to mention, I preferred to split the code into multiple code snippets with different examples rather than having a single huge one. Let’s hope it’d make it more clear </em>😅<em>.</em></p><ul><li>Enum contains a getter and the overridden toString() method:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49896204957799e2c5fbcf7defa3a108/href">https://medium.com/media/49896204957799e2c5fbcf7defa3a108/href</a></iframe><ul><li>Enum implements an interface:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c35aed0628db971b7a56ebbdf605b5a3/href">https://medium.com/media/c35aed0628db971b7a56ebbdf605b5a3/href</a></iframe><ul><li>Enum contains a constructor and final fields (<em>Enums can only declare final fields</em>):</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/290dc1811017f4431f211015b1ad24a9/href">https://medium.com/media/290dc1811017f4431f211015b1ad24a9/href</a></iframe><ul><li>Enum applies a mixin:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddc2e4b9bbe0be36dc52fbb023dd5e4/href">https://medium.com/media/4ddc2e4b9bbe0be36dc52fbb023dd5e4/href</a></iframe><ul><li>Finally, enums are still able to have extensions:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eb79a8440eb7f609e1b8e4e4600707d/href">https://medium.com/media/0eb79a8440eb7f609e1b8e4e4600707d/href</a></iframe><h4>⭐ <a href="https://github.com/dart-lang/language/blob/d16704ae6c9a5fd8f30b7ba9d33a5ab650c7447d/accepted/future-releases/named-arguments-anywhere/feature-specification.md">Named Arguments, Anywhere!</a> ⭐</h4><p>Previously, the named arguments had to be at end of the list of arguments, but not anymore 🎉! Now it’s possible to order the named and the positional arguments in whatever preferred way.</p><p><strong>Examples:</strong></p><ul><li>A custom doSomething function that takes positional and named parameters:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf21223497b52f9bc2af347c859f95a4/href">https://medium.com/media/cf21223497b52f9bc2af347c859f95a4/href</a></iframe><ul><li>One of the most popular ones, the Flutter Text widget constructor:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0516171aa587a0d6102e4a8a6c105b/href">https://medium.com/media/7a0516171aa587a0d6102e4a8a6c105b/href</a></iframe><h4>⭐ <a href="https://github.com/dart-lang/language/issues/1855">Super Constructors</a> ⭐</h4><p>Now there is less boilerplate code when it comes to the inherited class constructor. super can be used to implicitly pass a certain parameter to the superclass constructor. FYI, this feature <a href="https://github.com/flutter/flutter/pull/100905/files">reduced <em>thousands</em> of lines of code in the Flutter framework</a> 🤯.</p><p><strong>Example:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07e66c6180d307b27097cf69300caffc/href">https://medium.com/media/07e66c6180d307b27097cf69300caffc/href</a></iframe><p>And That’s pretty much it!</p><h4>For more information:</h4><ul><li><a href="https://dart.dev/guides/whats-new#may-11-2022-217-release">Dart: What’s new — May 11, 2022: 2.17 release.</a></li><li><a href="https://medium.com/dartlang/dart-2-17-b216bfc80c5d">Dart 2.17: Productivity and integration.</a></li></ul><p><strong><em>Thanks for Reading!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75b7ba045082" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magic Behind String to Double]]></title>
            <link>https://medium.com/@ahmadfayyas/magic-behind-string-to-double-898f306fa82d?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/898f306fa82d</guid>
            <category><![CDATA[double]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 11:28:52 GMT</pubDate>
            <atom:updated>2019-11-07T11:04:28.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_wMKtuiRAFWv-mIHxNOGQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@art_maltsev?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artem Maltsev</a> on <a href="https://unsplash.com/s/photos/magic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Although <em>“String to Double”</em> is one of the most popular obvious tasks, it could lead to funny magical stories!</p><h3>What’s the story?</h3><p>Once upon a time, I had a sub-task to generate doubles from given strings.</p><p>The requirement was:</p><blockquote>The value of the given string should be only one word, a car brand or a number. Any whitespace should be trimmed if exists.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*KHfIRzuCoByFcgWEcE21Vg.jpeg" /><figcaption>What a great logic?! Can we deal with two different separated pieces instead?!</figcaption></figure><p>It’s still confusing me to this day! Nevertheless, I had to deal with it “as it was” because it was “urgent and we don’t have time to fix it from the server-side”.</p><p>Whatever… I implemented it as the following logic:</p><p>Straightforwardly, I converted the given trimmed string to a double, as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e6e1210710d2716374a4a16bff3fcc/href">https://medium.com/media/97e6e1210710d2716374a4a16bff3fcc/href</a></iframe><p>Double(myString.trimmingCharacters(in: .whitespaces))</p><p>and everything worked as expected.</p><h3>Until MAGIC Happened ✨</h3><p>After a while, I was informed that there was a defect in the area of the task that I resolved (the one that contains the conversion logic). I was curious to know what it was, so I decided to follow the fastest way, which was reviewing it directly with the “data entry sorceress” 🧙 so she could do her spell 💫 in order to reproduce the defect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*ZtN2VbexqU0qwhBkC5-pWA.jpeg" /></figure><p>Thankfully, she was so cute 🌹 (I didn’t expect that to be honest), which made me insist on resolving the defect, before even knowing what it was.</p><p>After doing some “professional” negotiations with her, I discovered that the unexpected behavior occurred when inserting a car brand, I figured out that the input was “Infinity”.</p><h4>And here is the “lol” part</h4><p>I said</p><blockquote>Honestly, I have no idea how you managed to do that, but the brand name is “Infiniti” not “Infinity”!</blockquote><p>and naturally, I tried to explain that it was a bug and we would handle it ASAP. Suddenly, she blushed and she started to apologize! She even tried to make excuses that she “had to select the brand name from the given list instead of manually typing it”, thinking that her typo mistake was the main reason for the defect. Although I was about to roll on the floor laughing, I said</p><blockquote>no worries 🙂</blockquote><p>and I forgave her! Gentle Engineers!</p><h4>However, it’s still a bug 🐞</h4><p>After I had the new spell in hand, I got back to my laptop to learn more about it. The output of doSomething(with: “Infinity”) is <a href="https://developer.apple.com/documentation/swift/double/1541006-infinity">inf</a>, it’s the same as:</p><pre>Double.infinity</pre><p>We do know from our schools that <a href="https://en.wikipedia.org/wiki/Infinity">infinity</a> (∞) is a valid mathematical representation, it means something without any bound. However, that’s not what we usually expect (at least for my case or any similar one), we don’t care about these mathematical representations, we need to get an “actual” number!</p><p>So, I started to experiment with other strings that could be considered as valid doubles. I even attempted to pass other strings such as, symbols and emojis, to make sure of it. One of the things that I did which led me to good results, was passing the names of all static variables in the Double, therefore, I figured out that converting:</p><ul><li>“nan”</li><li>“-nan”</li><li>“inf”</li><li>“-inf”</li><li>“infinity”</li><li>“-infinity”</li></ul><p>gives a valid double value.</p><h4>Wait… What?!</h4><p>I thought it was clever to do my experiments on my own in this case, until the idea of:</p><blockquote>It’s about how the double initializer recognizes the given string…</blockquote><p>came to my mind, and I have no idea why it came so late! So, I reviewed the <a href="https://developer.apple.com/documentation/swift/double/2926277-init">wanted initializer’s documentation</a>, and… <strong>TADADADA!!!</strong></p><p>The surprise was that I found ALL my “clever experiments” already mentioned on there, and not only that, but even more cases that I didn’t even think of… My experiments were just gone with the wind 😨.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*X99VkYbaG_6N9hCsP4fDgg.gif" /><figcaption>What an Ending!</figcaption></figure><h3>To Sum Up</h3><p>Here are of the main lessons we can learn from this story:</p><ul><li><strong>The obvious one is: </strong>in some <em>rare </em>cases, converting a string which doesn’t even contain a single number to a double could give a valid result.</li><li>Doing coding experiments is cool, it is one of the reasons why a developer understands how things work more than the others, but <em>not</em> before reviewing the documentation, you might end up with meaningless experiments.</li><li>Even if you think of it as “too obvious”, I’d encourage you to still review the documentation. If you never did that before, you might see something new.</li><li>Don’t be frustrated while working on a task coming from a “really weird” requirement, it might give you the chance to meet cute people and learn new spells!</li></ul><p><strong><em>Thanks for Reading!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898f306fa82d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine Framework: First Impression.]]></title>
            <link>https://medium.com/better-programming/combine-framework-first-impression-2a4115ae5482?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a4115ae5482</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 11:07:38 GMT</pubDate>
            <atom:updated>2019-10-02T14:44:40.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Combine Framework: First Impressions</h3><h4>How we as developers will deal with the SwiftUI framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkDei7842_0u71_vF32RQw.png" /></figure><p><em>This is not a tutorial of coding with Combine framework. This is an iOS developer’s first impressions as to how we’ll deal with it.</em></p><p>A while ago, I published a <a href="https://medium.com/@ahmadfayyas/swiftui-first-impression-37a734fa6f02">piece</a> about my first impressions of the SwiftUI framework. In the article, I mentioned that SwiftUI could be more than a UI handler for our projects. After diving a little deeper into SwiftUI (and Swift 5.1), I recognized that <em>States </em>and <em>bindings </em>are (obviously) really nice. By using some of the provided <a href="https://github.com/DougGregor/swift-evolution/blob/property-wrappers/proposals/0258-property-wrappers.md">property wrappers</a> such as@State, @Bindingor @ObjectBinding, we can connect our views with our data models easily and more expressively.</p><p>One of the new topics that I noticed, was that in order to declare @ObjectBinding variable of your custom view model type, you should let it conform to <a href="https://developer.apple.com/documentation/swiftui/bindableobject">BindableObject</a> protocol. After that, you have to implement the didChange property, which is of type <a href="https://developer.apple.com/documentation/combine/passthroughsubject">PassthroughSubject</a>. If we trace the PassthroughSubject hierarchy, we’ll find out that it is a class, which is a concrete type of <a href="https://developer.apple.com/documentation/combine/subject">Subject</a> protocol, that conforms to the<a href="https://developer.apple.com/documentation/combine/publisher">Publisher</a> protocol — basically, it is a Publisher. So, what is that all about?</p><h3><strong>Are We Getting Far Away Arom SwiftUI?</strong></h3><p>The answer is yes. When you review thePublisher documentation, if you have sharp eyes (although, it’s clear enough) you’ll notice it relates to the family of the <a href="https://developer.apple.com/documentation/combine"><em>Combine</em></a><em> </em>framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*7AmWfPEoQdTZ4o01rFcKWw.png" /></figure><h4>Hello, Combine!</h4><p>Apple simply describes Combine as:</p><blockquote>Customize handling of asynchronous events by combining event-processing operators.</blockquote><p>Honestly, my first impression when I started reading the “technical terms” used in the framework documentation--<em>Publisher</em> , <em>Just</em> <em>Subscriber</em> , <em>Subscription</em>, <em>Operators</em> ,<em>Cancellable</em> , <em>Scheduler — </em>my mind automatically connected them as keywords with the world of FRP!</p><p>So, <em>yes</em>, if you’re familiar with one of the FRP frameworks such as <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a> or <a href="https://github.com/ReactiveCocoa/ReactiveCocoa">ReactiveCocoa</a> — congratulations, you now know the main reason of the Combine framework existence! Currently, we can say that Apple does support the FRP paradigm natively without the need of dealing with a third-party framework for building our projects!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*n4ZiLItKn1s3RDubzt9aaQ.gif" /><figcaption>Finally, Apple!</figcaption></figure><h4>But wait…what if I have no idea what FRP is?</h4><p>Well, I would say it’s a good opportunity to find out!</p><p>Basically, dealing with <a href="https://en.wikipedia.org/wiki/Functional_reactive_programming">Functional Reactive Programming (FRP)</a> lets you worry less about managing data, and allows you to concentrate on how your apps should work. Here are some of the points that describe the meaning of “worry less about managing data”:</p><ul><li>The parts of your app might be affected.</li><li>The amount of (“tedious” in some cases) boilerplate code that you may need to implement (Hello Delegates, Targets-Actions, KVOs ...!).</li><li>Caring about synchronous/asynchronous changes and how to connect their impact to the default app’s data flows.</li></ul><p>Additionally, it might worth mentioning that when comparing FRP with the usual standard approaches, most of the time you’ll need to write <em>less</em> code to achieve the same results. It’s about performing things “<em>declaratively”</em>.</p><h4><strong>Less code?!</strong></h4><p>To clarify, take a look at one of the most popular cases we might achieve in our apps, which is dealing with multiple asynchronous calls. Obviously, we should think about one of the concurrency techniques, one of the proper choices would be the <a href="https://developer.apple.com/documentation/dispatch/dispatchgroup">GCD DispachGroup</a>. Whether the tasks are on the same queue or on different queues, we are still able to observe the execution and completion of them in the group. Example:</p><pre>let queue = DispatchQueue(label: &quot;reverseDomain&quot;, attributes: .concurrent)<br>let group = DispatchGroup()<br><br>queue.async (group: group) {<br>    performAsync01()<br>}<br><br>queue.async (group: group) {<br>    performAsync02()<br>}<br><br>queue.async (group: group) {<br>    performAsync03()<br>}<br><br>group.notify(queue: DispatchQueue.main) {<br>    // tasks executions are finished<br>}</pre><p>Keep in mind that the output of the asynchronous task might be a returned value. This means that in addition to the above code, we might need to declare an instance variable to set the returned value in order to access it.</p><p>So, what about Combine?</p><pre>let myPublisher = Publishers.Zip3(photoSubject, stringSubject, voidSubject)<br>myPublisher.sink { (asset, string, _) in<br>    // tasks executions are finished<br>    // additionally, we can directly access the tasks (subjects) outputs<br>}</pre><p>Note that photoSubject , stringSubject and voidSubject are predefined <a href="https://developer.apple.com/documentation/combine/subject">Subjects</a> (which are basically Publishers). We just applied zipping for the upstream publishers by using <a href="https://developer.apple.com/documentation/combine/publishers/zip3">Zip3</a>, and that’s all! The beauty of it is not only about the amount of code that has been written, but it’s also about the used paradigm for achieving such a task.</p><p>Moreover, when you work with publishers you’ll find out that there are many useful <em>operators </em>to act on the received values from publishers and republish them — it’s awesome!</p><h3>What Does This Mean to Me as a Developer?</h3><p>We can see that we’ll have a chance (and it might be the only required way in the future) to change the used approaches for developing our iOS apps by using these provided frameworks. Some developers are keen to learn it, some are getting bored of having to keep dealing with all this new stuff, and the rest are just, “yeah whatever…”.</p><p>I won’t say that learning and working with Combine is a must (at least for now), but whether we like it or not — keep in mind it exists. Perhaps in the near future we’ll see a new generation of iOS developers who <em>only </em>know how to settle things with Combine and nothing else! Could that be possible?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*2-zqbPyfFdS5Xn7xFgwAwQ.jpeg" /><figcaption>Us, the old generation.</figcaption></figure><p>Maybe you’ve heard this opinion:</p><blockquote>In order to apply an alternative architectural design pattern such as MVVM, I have to know the “reactive programming” thing.</blockquote><p>It doesn’t have to be totally correct, but it makes sense! That’s because applying a pattern such as MVVM appropriately requires <em>two-way </em><a href="https://en.wikipedia.org/wiki/Data_binding"><em>data binding</em></a><em>, </em>which is a pain without following the reactive programming approach to achieve it.</p><h4><strong>By the way</strong>, am I allowed to use Combine without using SwiftUI?</h4><p>Yes, you are not limited to use Combine only with SwiftUI. You can use Combine framework with UIKit, which means that you’re able to build the UI part of your application as you usually do meanwhile leveraging Combine. Rejoice!</p><p>Additionally, the good news is that there is compatibility between the Foundation framework and Combine framework. Citing from the Combine documentation:</p><blockquote>Several Foundation types expose their functionality through publishers, including <a href="https://developer.apple.com/documentation/foundation/timer">Timer</a>, <a href="https://developer.apple.com/documentation/foundation/notificationcenter">NotificationCenter</a>, and <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a>. Combine also provides a built-in publisher for any property that’s compliant with Key-Value Observing.</blockquote><blockquote>You can combine the output of multiple publishers and coordinate their interaction. For example, you can subscribe to updates from a text field’s publisher, and use the text to perform URL requests. You can then use another publisher to process the responses and use them to update your app.</blockquote><p>This will make our lives even easier when dealing with some of the Foundation types with Combine. I hope we’ll see more of this in the future.</p><h3>And Finally</h3><p>As I mentioned in the <a href="https://medium.com/@ahmadfayyas/swiftui-first-impression-37a734fa6f02">SwiftUI p</a>iece, the declarative paradigm is already popular. Even if it’s new to you, working with it will not only be reflected on your iOS development knowledge, but will expand your general programming skills, as well as your problem-solving skills. When it comes to iOS development, the beauty of it is that we have more dynamic facilities to achieve our desired patterns and approaches. It’s more like “learn it once, apply it anywhere”.</p><p><em>Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a4115ae5482" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/combine-framework-first-impression-2a4115ae5482">Combine Framework: First Impression.</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI, First Impression.]]></title>
            <link>https://medium.com/@ahmadfayyas/swiftui-first-impression-37a734fa6f02?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a734fa6f02</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Sun, 09 Jun 2019 17:43:24 GMT</pubDate>
            <atom:updated>2019-10-03T13:15:08.447Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftUI Framework: First Impressions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i525BQ1CPdSdJ-m1at1Lzg.png" /></figure><p><em>This is not a tutorial of coding with SwiftUI, it is just an iOS developer’s first impression about how we’ll deal with the framework.</em></p><h3>Hello, SwiftUI!</h3><p>At June 03, 2019 Apple announced a brand new UI framework works across all Apple’s platforms, <a href="https://developer.apple.com/xcode/swiftui/">SwiftUI</a>, evolutionary a curial change in the heart of iOS development.</p><p>For me as usual, when hearing of such a change: “Wuhoo! A new thing 😃… Oh really 😑”. I decided to <em>briefly</em> take a look at its documentation just checking the headlines and then directly getting my hands dirty by coding.</p><blockquote>Side-bar tip: we (developers) usually love to go directly to the final results; At certain point, even copying-pasting a valid answer from StackOverflow without knowing what on earth is going on would be ok!.</blockquote><p>At the very first look at the code snippets and the examples, I saw kind of non-usual coding style (at least for iOS development). After getting back couple of steps, I recognized that I read the intro too fast hence I skipped one of the most describing terms in the documentation, “<strong><em>declarative</em></strong>”.</p><h3>Huh, “Declarative”?!</h3><p>Wait a sec… Should I write such a code to create a table view?!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZProRXOocBhRyCzqx1jVNg.png" /><figcaption><a href="https://developer.apple.com/xcode/swiftui/">https://developer.apple.com/xcode/swiftui/</a></figcaption></figure><p>It may look cool and weird somehow. For me, the coolest part of it is: Less code! I don’t have to write so much boilerplate code (yes, I’m talking about you DataSources and Delegates). Nevertheless, this doesn’t look so familiar to create a table view, right? Actually, the mentioned coding style is an example of the <em>declarative </em>paradigm;<em> </em>The “usual” paradigm for us is called the <em>Imperative </em>paradigm<em>.</em></p><p>Although<em> </em>There are many articles, blog posts, and questions/answers out there describing the difference between <em>declarative </em>and<em> Imperative </em>I’d remind that:</p><blockquote><strong><em>Declarative</em></strong><em>: </em>What<em> do I (code writer) want to do. Not interested in how you (service provider: compiler, framework, etc…) do it.</em></blockquote><blockquote><strong><em>Imperative</em></strong><em>: </em>How<em> do I want to do it. I describe each step of how should it be done.</em></blockquote><p>For clarification, let’s take a look to a pretty simple example to see what’s the main different between declarative<strong><em> </em></strong>and imperative:</p><p>Consider that we have an array of Ints and we want to get the elements with a value of larger than 100 of it, then we want to add “is larger than one hundred” after each one of them. Simple enough, how to resolve it? Like this:</p><pre>let result = myArray.filter { $0 &gt; 100 }.map { &quot;\($0) is larger than one hundred&quot; }</pre><p>This is <strong>declarative</strong> coding! Think of it as you just told the compiler what is your expected result without specifying the details of it: “That’s <em>what </em>I want to get. <em>How</em>? I don’t care!”.</p><p>On the other hand, you can also resolve it as:</p><pre>var result = [String]()</pre><pre>for element in myArray {</pre><pre>    if element &gt; 100 {</pre><pre>        let newElement = “\(element) is larger than one hundred”</pre><pre>        result.append(newElement)</pre><pre>    }</pre><pre>}</pre><p>and you’ll get the same result, you told the compiler exactly what are you aiming to do <strong>imperatively</strong> (loop through the array, check the value of each element, interpolate it in a string and add it to a new array).</p><p>Additionally, bare in mind that the first code snippet is better choice because of:</p><ul><li>Readability: For most of the developers, the first code snippet is more readable (and I hope it is for you!).</li><li>Performance: The first code snippet avoid <em>mutability </em>(var result).</li></ul><p>So you might already write declarative code without even recognizing it. Basically, that’s it.</p><p>Ok, let’s back to our table view thing. As I mentioned, I’d bid you wrote a lot of DataSource/Delegate methods implementation. We are describing the details for doing it, such as the number of the rows/sections, how the cell should look like (configuring the cell), and what should happen when tapping it</p><p>A quick reminder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*03zAFlQmKEfrFVSkUK0_bQ.jpeg" /><figcaption><a href="https://www.c-sharpcorner.com/blogs/tableview-prototypecell-in-swift">https://www.c-sharpcorner.com/blogs/tableview-prototypecell-in-swift</a></figcaption></figure><p>Probably, this is almost the simplest way to define how your table view should look like by following the “usual” Imperative<strong> </strong>paradigm<strong>.</strong></p><p>In general, the main idea to keep in mind when aiming to create your table view declaratively is<strong>: </strong>Actually, we declare the list, we mention the model objects to be used for each row as well as the action for tapping the row; No setup, no cell configurations or callbacks! At least that’s the simplest form of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*wvtVx4RBvKM1YydxUoE6_w.gif" /></figure><h3>What does it mean to me as a developer?</h3><p>I assume that some of the developers are keen to learn it, some of them are getting bored of dealing with new technology, and the rest of us like “ya whatever…”.</p><p>Regardless of which type you are, IMO I would recommend to learn it and deal with it. Apple focuses (and actually enforces at certain conditions) to keep the developers up to date with the latest provided technologies, if you have been working with iOS development for couple of years, you are already know exactly what I’m talking about. Maybe in future it will be the <em>only </em>way to setup our apps UI, or at least the current one we know may get deprecated.</p><p>Moreover, it’s worth to mention that SwiftUI could be more than just the “UI handler” part in our projects; Citing from SwiftUI - <a href="https://developer.apple.com/documentation/swiftui/state_and_data_flow">State and Data Flow</a> documentation:</p><blockquote><strong><em>States</em></strong><em> and </em><strong><em>bindings</em></strong><em> connect views to your app’s underlying data model. When you declare a state, SwiftUI stores it for you and manages the state’s connections to its view. When the state updates, the view invalidates its appearance and updates itself. You can also connect animations to the state to animate how the view portrays the change.</em></blockquote><blockquote><em>Create bindings from members of your state to connect to individual views. </em><strong><em>Bindings offer two-way connections</em></strong><em>, so that onscreen controls can mutate the state. Bindings also have transactions to pass values between views.</em></blockquote><p>Based on that, when reading “<em>States and bindings</em>” and “<em>Bindings offer two-way connections</em>” I guess that the first thing came to your mind is… YES! A new era with more than the standard MVC!</p><p>Does it mean that applying an alternative architectural patterns would be much easier and native without extra headache?!…</p><h3>Finally</h3><p>Declarative paradigm is already a popular one even if it’s new to you, for instance if you are a bit familiar with the JavaScript world, you’ll notice that many of its libraries and frameworks are following the declarative paradigm. My point here is to mention that the benefits of working with it will not only be reflected on your iOS development knowledge, it will definitely expand your general programing skills.</p><p>Without a doubt, there is a lot to learn for now -even if we have prior knowledge of dealing with “declarative” coding style-, let’s just prepare ourselves for it; Personally, I’m pretty sure that it will enormously make our life easier.</p><h4>Furthermore</h4><p>As expected, there is a wide potential for going into the SwiftUI world. I’d like point out to <a href="https://github.com/chinsyo/awesome-swiftui"><strong>awesome-swiftui</strong></a><strong> </strong>great repo, it comprehensively contains official/non-official websites, tutorials, libraries, sessions, and articles (including this one 😎) about SwiftUI.</p><p><strong><em>Thanks for reading!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a734fa6f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Codables for Persisting Custom Objects in UserDefaults]]></title>
            <link>https://medium.com/@ahmadfayyas/using-codables-for-persisting-custom-objects-in-userdefaults-aeb3625fbf36?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeb3625fbf36</guid>
            <category><![CDATA[userdefaults]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 18:17:20 GMT</pubDate>
            <atom:updated>2019-04-30T08:26:49.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Z3s3lk2dMigmq-dzY1L0Uw.jpeg" /></figure><p>Most of the apps we build require to persist data, leading to “What to use for data persistency?” It’s a crucial decision for setup the architectural layers for your apps, especially when recognizing there is a need to deal with “big” and/or “non-trivial structured” data; However, there are some of them require to persist a “small simple enough” data (one or two custom objects would be sufficient). Obviously, there are more than just one approach to follow for achieving such a task, for instance <em>CoreData</em>, <em>Realm</em>, <em>SQLite</em>, <em>UserDefaults</em>, writing data to <em>JSON</em> or <em>plist</em> files…</p><p>Hence you might think as:</p><blockquote>Ugh! I don’t want to use a FULL (and possibly heavy) database for saving a single object or even couple of them!</blockquote><p>I’d obviously agree this! Personally, I would avoid using CoreData (for instance) to persist a single object. Let’s take a look to a pretty simple approach, dealing with UserDefaults is simple enough right? 🙂</p><p><strong>Codable to the rescue </strong>⛑️</p><p>Back in days (and you might already know that), we dealt with <a href="https://developer.apple.com/documentation/foundation/nscoding">NSCoding</a> and <a href="https://developer.apple.com/documentation/foundation/nskeyedarchiver">NSKeyedArchiver</a>/<a href="https://developer.apple.com/documentation/foundation/nskeyedunarchiver">NSKeyedUnarchiver</a> to persist custom objects. Nowadays (more specifically, starting from Swift 4), <a href="https://developer.apple.com/documentation/swift/codable">Codable</a> makes our life easier for persisting custom objects! It might be similar to the approach of using NSCoding , but it is more natural when working with Swift and personally, I find it simpler.</p><p><strong>Whatever, What’s the magic? ✨</strong></p><p>As a reminder, Codable is a <a href="https://medium.com/@ahmadfayyas/swift-quick-elegant-code-typealias-8e6d59f07f32">type alias </a>for both Encodable and Decodable protocols, saying “we are going to use Codable” means that we will both <em>encode</em> and <em>decode</em>.</p><p>How it works: we <em>encode </em>the object therefore transforming it to Data , which is acceptable to be set in the UserDefault; For getting it back, we <em>decode</em> it back again into our custom type. That’s pretty much it!</p><p><strong>Codables with UserDefault in action:</strong></p><p>For demonstration, let’s apply this approach on implemented type. Consider that we have the following Employee struct that we need to persist its instances:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c9638db4404966bd49f581a454d87d/href">https://medium.com/media/91c9638db4404966bd49f581a454d87d/href</a></iframe><p>According to what mentioned for doing the “magic”, what do we need for now is to make Employee to be codable (conforms to Codable), simply as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6d0fab76b4615a0a583dcc3ed6f71b/href">https://medium.com/media/ce6d0fab76b4615a0a583dcc3ed6f71b/href</a></iframe><p>Note that Department also needs to conforms to Codable since Employee has a department property of type Department .</p><p>At this point, we can set any Employee instance into user defaults! Finally, we need to implement the methods for persisting/fetching an Employee instance into/from user defaults:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e65ca8b191faa13f38bdba5d06e2cf5f/href">https://medium.com/media/e65ca8b191faa13f38bdba5d06e2cf5f/href</a></iframe><p>And we’re done!</p><p>You might ask</p><blockquote>Since we are using JSONEncoder/JSONDecoder, are we dealing with JSON here?</blockquote><p>Technically speaking, yes we do; However, you don’t have to bother yourself with thinking about how it works, the main part here is that you are working with aData instance and a custom type instance.</p><p><strong>Let’s check it out:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1131d6f516ea0a5bbc9ffa3113882051/href">https://medium.com/media/1131d6f516ea0a5bbc9ffa3113882051/href</a></iframe><p>Obviously, the ID should be different in your playground/project from the one on the code snippet, however it has to be identical for both the persisted and the fetched employee (technically, since they refer to the same employee) .</p><p>Again, if you still excited to see how see the JSON result for the persisted employee, you could add extra string declaration in the fetch method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee5eef26c1e9e69e3c0252dffddf6909/href">https://medium.com/media/ee5eef26c1e9e69e3c0252dffddf6909/href</a></iframe><p>Certainly, john is editable (with <em>variable</em> var john):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4669236fbc92679fc3a140858760fa2/href">https://medium.com/media/d4669236fbc92679fc3a140858760fa2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*ljTFIMmjzU5_IxkLssllAA.gif" /></figure><h4>Furthermore, What about a collection of custom objects?</h4><p>Is the same approach applicable for a collection of codable objects? The good news is: Yes it is!</p><p>Let’s do it for Array :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/260f16cd5dfb470ef1cd145771c29637/href">https://medium.com/media/260f16cd5dfb470ef1cd145771c29637/href</a></iframe><p>As you can see, it’s almost the same functionality for persisting/fetching in the Employee struct, furthermore we are dealing with an array instead of a single instance.</p><p>Therefore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f87633216f64d341e84eac666ad03f5c/href">https://medium.com/media/f87633216f64d341e84eac666ad03f5c/href</a></iframe><p>Nicely works 👍.</p><p><strong>⚠️ Here is a final note to keep in mind:</strong></p><p>You should <em>not</em> persist sensitive data (such as passwords, credit card numbers, etc…) in the user defaults, still a <em>public</em> resource anyway. There are many articles out there talking about why you shouldn’t do it, you could check this one: <a href="https://www.andyibanez.com/nsuserdefaults-not-for-sensitive-data/">https://www.andyibanez.com/nsuserdefaults-not-for-sensitive-data/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeb3625fbf36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift, more elegant code: OptionSet]]></title>
            <link>https://medium.com/@ahmadfayyas/swift-more-elegant-code-optionset-205e4866b4aa?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/205e4866b4aa</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Mon, 25 Jun 2018 14:31:06 GMT</pubDate>
            <atom:updated>2024-02-09T11:21:22.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilkHJoiLurxjY5VRqkiqJA.jpeg" /></figure><p><em>Would you like to know how to deal with Bitmasks in Swift? Have you ever heard of </em><em>OptionSet it and you want to know more? Well, this is for you!</em></p><h4>What is OptionSet?</h4><p>OptionSet is a Protocol that conforming to makes you able to do <a href="https://en.wikipedia.org/wiki/Mask_(computing)">bitmasking</a>. It is a representation of a bit set, each single bit would represent an option. Sounds unclear? Let’s code:</p><h4>How to implement OptionSet?</h4><p>Here is a basic implementation for a Structure (MyStruct) that conforms to the OptionSet :</p><pre>struct MyStruct: OptionSet {<br>    let rawValue: Int</pre><pre>    static let firstOption = MyStruct(rawValue: 1 &lt;&lt; 0)<br>    static let secondOption = MyStruct(rawValue: 1 &lt;&lt; 1)<br>    static let thirdOption = MyStruct(rawValue: 1 &lt;&lt; 2)<br>}</pre><p>Let’s explain what happened in the above code:</p><p>Conforming to OptionSet requires declaring rawValue as any type of <a href="https://developer.apple.com/documentation/swift/fixedwidthinteger">FixedWidthInteger</a>, such as Int, Int8, or Int16. Next, you would need to declare the desired options <em>statically</em>, That’s all to create your OptionSet!</p><p><strong>“Why does it have to be static? And what is the </strong><strong>&lt;&lt; thing?”</strong></p><blockquote><strong><em>Sidebar Note</em></strong>: Before going straightforward to the OptionSet options declaration, I would suggest to get familiar with the “zero one” world — if you are not so far. Understanding the binary representation of a decimal value would make it easier to understand and implement the OptionSet options. Here is a good article: <a href="https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa">Bits, Bytes, Building With Binary</a>.</blockquote><p>Logically, the option should be declared as <a href="https://en.wikipedia.org/wiki/Static_variable">static</a>, because you would access it directly without the need to instantiate from a conformed structure (MyStruct in our example) — as we’ll see in a moment. Next, the option should be declared as an instance of the conformed structure (MyStruct in our example) with assigning a desired “Binary counting” rawValue, and that’s the purpose of using the &lt;&lt; <em>bitwise left shift operator.</em></p><p>Although I would recommend checking the documentation for <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID29">Bitwise Operator</a> — Bitwise Left and Right Shift Operators, I would mention a quick brief of how it works: it moves all bits in a number to the left, for instance:</p><pre>let one = 0b0001 // 1<br>let shiftedZero = one &lt;&lt; 2 // 4 (0b0100)</pre><pre>let twentyOne = 0b0010101 // 21<br>let shiftedTewntyOne = twentyOne &lt;&lt; 2 // 84 (1010100)</pre><p>we just shifted the bits in one and twentyOne two steps. In other words, it added two zeros on the right side of the value.</p><p>This means that implementing the options:</p><pre>static let firstOption = MyStruct(rawValue: 1 &lt;&lt; 0) // 1<br>static let secondOption = MyStruct(rawValue: 1 &lt;&lt; 1) // 10 <br>static let thirdOption = MyStruct(rawValue: 1 &lt;&lt; 2) // 100</pre><p>is identical to:</p><pre>static let firstOption = MyStruct(rawValue: 1)<br>static let secondOption = MyStruct(rawValue: 2)<br>static let thirdOption = MyStruct(rawValue: 4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3kX_qhAwpwAKONeSioaYQ.jpeg" /></figure><p><strong>“So, why we are setting the </strong><strong>rawValue by using </strong><strong>&lt;&lt; operator?”</strong></p><p>It could be more convenient to ensure following the binary counting formula (1, 2, 4, 8, 16…). Setting a raw value that does not follow the binary counting formula would cause a logical error! It doesn’t mean that it reproduces any crashes or even a compile-time error, but you won’t get the benefit (purpose) of declaring an OptionSet. For example, setting the “3” as a rawValue for one of the declared options would be a conflict with the combination of the “1” and “2” options.</p><h4>Why to use OptionSet?</h4><p>You could simply consider it as a combination of a finite number of options represented in a single value.</p><p><em>Note that we are not talking about collections that could contain multiple elements, such as an array, it is just one value).</em></p><p><strong>Example:</strong></p><p>There is a requirement to let the user choose his favorite pet, it should be one of the following options (<em>pussycat</em>, <em>puppy</em>, <em>hamster,</em> or <em>chameleon</em>). The first “make sense” comes to mind option is implementing an <em>enum</em>:</p><pre>enum Pet {<br>    case pussycat, puppy, hamster, chameleon<br>}</pre><pre>let favortiePet: Pet = .puppy</pre><p>However, things change vastly 😑!</p><p>Our requirement now is that the user can choose <em>multiple</em> favorite pets…</p><p>As a workaround, it can be updated to be declared as a proper collection type (Array or maybe Set):</p><pre>let favortiePets: [Pet] = [.pussycat, .puppy]</pre><p>It’s legal and “not that bad”, nevertheless it can be optimized!</p><p>Well, let’s see how to handle it using OptionSet:</p><pre>struct Pet: OptionSet {<br>    let rawValue: UInt8</pre><pre>    static let pussycat = Pet(rawValue: 1 &lt;&lt; 0)<br>    static let puppy = Pet(rawValue: 1 &lt;&lt; 1)<br>    static let hamster = Pet(rawValue: 1 &lt;&lt; 2)<br>    static let chameleon = Pet(rawValue: 1 &lt;&lt; 3)<br>}</pre><pre>let singlePet: Pet = .puppy<br>let multiplePets: Pet = [.puppy, .pussycat]</pre><p><em>Note that </em><em>multiplePets type is </em><em>Pet , NOT </em><em>[Pet] (don’t get tricked by seeing the square brackets 👻).</em></p><p>The rawValue of:</p><ul><li>singlePet is <em>2</em> (1 &lt;&lt; 1).</li><li>multiplePets is <em>3 </em>(1 &lt;&lt; 1 + 1 &lt;&lt; 0).</li></ul><p>Implies that:</p><ul><li><em>pussycat</em>: rawValue = 1</li><li><em>hamster</em> and <em>chameleon</em>: rawValue = 12 (4 + 8)</li><li><em>ALL pets</em>: rawValue = 15 (1 + 2 + 4 + 8)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*c5nl9B07CD5AYhTzr4d-_Q.jpeg" /></figure><h4>Furthermore</h4><p>Another pretty cool feature that you will get when using OptionSet is the <em>set-related operations</em>, for instance (based on Pet struct):</p><pre>let options1: Pet = [.pussycat, .puppy]<br>let options2: Pet = [.puppy, .hamster, .chameleon]</pre><pre>let intersection = options1.intersection(options2)<br>print(intersection) // Pet(rawValue: 2) 👉 puppy</pre><pre>let union = options1.union(options2)<br>print(union) // Pet(rawValue: 15) 👉 pussycat, puppy, hamster &amp; chameleon</pre><pre>let subtracting = options1.subtracting(options2)<br>print(subtracting) // Pet(rawValue: 1) 👉 pussycat</pre><pre>let contains = options1.contains(.hamster)<br>print(contains) // false</pre><h4>Wrapping Up:</h4><p>OptionSet is the way to achieve bitmasks. As we’ve taken a look, it could be a good choice for storing a finite list of related options as a single value. However, keep in mind to use it wisely! In the end, it is <em>not </em>a collection.</p><h4>Reference:</h4><ul><li>Swift Documentation: <a href="https://developer.apple.com/documentation/swift/optionset">OptionSet Protocol</a>.</li></ul><h4>Author ✍️</h4><p>Appreciate your feedback 👏 Stay tuned for more “Swift, more elegant code” topics.</p><p>Thanks for Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205e4866b4aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift, more elegant code: Autoclosure]]></title>
            <link>https://medium.com/@ahmadfayyas/swift-more-elegant-code-autoclosure-6f20d038093d?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f20d038093d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Wed, 25 Apr 2018 14:00:29 GMT</pubDate>
            <atom:updated>2018-06-26T06:12:28.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kqk5MnuPQ_MCRZg3XJl03w.jpeg" /></figure><p><em>So far you are familiar with the definition of “closure” and how basically work with it, but you feel that you could expand your familiarity by knowing what else can be done using closures, well this article is for you!</em></p><p>Personally, I find closures are one of the coolest features in Swift, I believe working with closures makes the code to be more expressive, responsive and easy to deal with. Even standard functions are considered as special closures (named closures).</p><h4>What is autoclosure?</h4><p>For the first time I read about the autoclosure, I found it a little confusing to understand the purpose of using it, until I figured that there is no need to overthink about it, it is really simple.</p><p>Apple defines the autoclosure as:</p><blockquote>An <em>autoclosure</em> is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.</blockquote><p>Actually it is nothing more than a <a href="https://en.wikipedia.org/wiki/Syntactic_sugar"><em>syntactic sugar</em></a> for passing a closure as an argument; When passing an autoclosure as a function parameter, you don’t have to type the curly braces!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*yU3e5KydlMQsEInuUbbj7A.jpeg" /></figure><h4>How to implement autoclosure?</h4><p>Actually there is nothing to do for the closure itself that you want to pass it as a parameter, it is related to the function that takes the closure as a parameter; By marking the closure parameter as @autoclosure:</p><blockquote>func perform(closure: @autoclosure ()-&gt;())</blockquote><p>You are telling the compiler that closure<strong> </strong>is an autoclosure, simple as that!</p><h4>Why to use autoclosure?</h4><p>As mentioned above -in “What is autoclosure?”-, for some cases, it becomes more handy to pass a closure as a parameter without the curly braces thing; I think one of the best places for using an autoclosure is <em>operators</em>.</p><p><strong>Example:</strong></p><p>For the purpose of making it more clear, let’s walk through this case:</p><p>Imagine that we are working on a part of a product related to organizing HR system, containing Employee<strong> </strong>struct as:</p><pre>struct Employee {<br>    var id: Int<br>    var name: String<br>    var salary: UInt<br>}</pre><p>and new requirement has been requested as:</p><blockquote><em>we need to create an operator as (</em><em>-!) that decrements the employee salary, it should be used like this:</em></blockquote><blockquote><em>Employee -! amount</em></blockquote><blockquote><em>amount would be calculated based on many factors. However if the salary of the employee is less than 1000, nothing should happen</em></blockquote><p>Pretty cool! Let’s call our new (-!)operator “decrement operator”. So, we will implement it as:</p><pre>infix operator -!<br>extension Employee {<br>    static func -!(lhs: inout Employee, rhs: ()-&gt; UInt) {<br>        if lhs.salary &gt; 1000 {<br>            lhs.salary -= rhs()<br>        }<br>    }<br>}</pre><p>Based on the mentioned requirement, our implementation for the decrement operator seems to be fine. However, when trying to use it, we will notice that an “ugly” code has to be written 😥:</p><pre>var jack = Employee(id: 101, name: &quot;Jack Thompson&quot;, salary: 2000)<br>jack -! {100} // what are these curly braces!</pre><pre>print(jack)<br>// Employee(id: 101, name: &quot;Jack Thompson&quot;, salary: 1900)</pre><p>Although it works as expected, the necessity of typing “{}” is inappropriate, how can we get rid of it?! Well, that’s exactly the purpose of marking a closure as @autoclosure. All we should do is to change the decrement operator method signature to be:</p><pre>static func -!(lhs: inout Employee, rhs: @autoclosure ()-&gt; UInt)</pre><p>thus we will be able to:</p><pre>jack -! 100</pre><p>Our decrement operator is more natural to be used now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*FHzV9cDn-Vme_nSvQLr6Jw.jpeg" /></figure><h4>Sidebar tip:</h4><p>Referring to how we implemented the decrement operator, you might be wondering:</p><blockquote>Why do we need to declare the right hand side as (@autoclosure ()-&gt; UInt) instead of directly (UInt)?</blockquote><p>by doing it, we can implement our operator as:</p><pre>static func -!(lhs: inout Employee, rhs: UInt) {<br>    if lhs.salary &gt; 1000 {<br>        lhs.salary -= rhs<br>    }<br>}</pre><p>implies that:</p><pre>jack -! 100</pre><p>should work fine.</p><p>Good question! 👍</p><p>The reason behind it is closures are <em>lazily </em>evaluated; In our case, the right hand side needs to be evaluated <em>only</em> if the employee salary is more than 1000, so declaring rhs as UInt instead of @autoclosure ()-&gt; UInt, getAmountToDecrmement() leads to let it <em>always</em> be evaluated even if the employee salary is less than 1000!</p><p>You don’t believe it?! Let’s give it a try by checking the log for both cases:</p><ul><li>In case of declaring the decrement operator as static func —! (lhs: inout Employee, rhs: UInt) :</li></ul><pre>func getAmountToDecrmement() -&gt; UInt {<br>    print(&quot;consider there is a lot to be calculated here…&quot;)<br>    return 101<br>}</pre><pre>var erik = Employee(id: 102, name: &quot;Erik Smith&quot;, salary: 500)<br>erik -! getAmountToDecrmement()</pre><pre>print(erik)<br>// Employee(id: 102, name: &quot;Erik Smith&quot;, salary: 500)</pre><p>At this point, it would log:</p><pre>consider there is a lot to be calculated here…<br>Employee(id: 102, name: &quot;Erik Smith&quot;, salary: 500)</pre><p>As you can see, “<strong>consider there is a lot to be calculated here…</strong>” has been printed, without decrementing the salary (Erik salary is less that 1000).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*HsaDbZMc-Hk3ZfUQ0h_PRg.jpeg" /></figure><ul><li>In case of declaring the decrement operator as static func —! (lhs: inout Employee, rhs: @autoclosure ()-&gt; UInt)<strong> :</strong></li></ul><pre>var erik = Employee(id: 102, name: &quot;Erik Smith&quot;, salary: 500)<br>erik -! getAmountToDecrmement()</pre><pre>print(erik)<br>// Employee(id: 102, name: &quot;Erik Smith&quot;, salary: 500)</pre><p>It would log:</p><pre>Employee(id: 102, name: &quot;Erik Smith&quot;, salary: 500)</pre><p>Without the “<strong>consider there is a lot to be calculated here…</strong>”.</p><p>Unlike the first case, since rhs<strong> </strong>is a closure, its evaluation <em>delayed </em>until the argument has needed to be used.</p><h4>Wrapping up:</h4><p>Using autoclosures makes our code to be more natural; As pretty simple example, the Swift logical AND operator (&amp;&amp;) declared as:</p><pre>func &amp;&amp;&lt;T : BooleanType&gt;(lhs: T, rhs: @autoclosure () -&gt; Bool) -&gt; Bool</pre><p>since if the lhs there is no need to evaluate the rhs (the result is false). We -as developers- are using it gracefully without even caring about whether if it deals with closures or not, that’s the obvious when using such a method.</p><p>Don’t hesitate to use autoclosures in the right place, they more simpler than being scary 👻.</p><h4>Reference:</h4><p>The Swift Programming Language — Closures: <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID543">Autoclosures</a>.</p><h4>Author ✍️</h4><p>Appreciate your feedback 👏 Stay tuned for more “Swift, more elegant code” topics.</p><p>Thanks for Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f20d038093d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift, more elegant code: Typealias]]></title>
            <link>https://medium.com/@ahmadfayyas/swift-quick-elegant-code-typealias-8e6d59f07f32?source=rss-c523b085d034------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e6d59f07f32</guid>
            <category><![CDATA[manager]]></category>
            <category><![CDATA[typealias]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[compound-types]]></category>
            <dc:creator><![CDATA[Ahmad Fayyas]]></dc:creator>
            <pubDate>Wed, 10 Jan 2018 20:38:45 GMT</pubDate>
            <atom:updated>2018-05-07T07:28:19.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilkHJoiLurxjY5VRqkiqJA.jpeg" /></figure><p><em>Are you facing troubles with long-signature functions? do you think that renaming some of the types would be a good idea? well… just take a look at </em><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID361"><em>typealias</em></a><em>.</em></p><h4>What is typealias?</h4><p>For the first time I figured out that there is something called “Aliases” it was a bit weird for me, even after knowing what it does, it seemed to me that there is no “good” point of using it; So far I’m a fan of it!</p><p>Before jumping to Swift typealias, I would like to note that the alias is <em>not</em> an exclusive term for Swift programming language, actually it is a <em>computing</em> term, you could find the logic of “Aliasing” in many other old-school and modern (such as Swift) programming languages…</p><p>Typealias is a named alias of an existing type, meaning that by using it you would be able to name types to be more convenient to your program. Keep in mind that typealias is <em>not</em> new types, it is just name to existing type, you could consider it as an alternative name for a type (it could be a “shortcut” as you will read soon).</p><h4>How to implement typealias?</h4><p>Simply, you would implement a typealias as:</p><blockquote>typealias yourCustomName = existing type</blockquote><p>and that all it takes!</p><p><strong>Let’s start doing some pretty simple code:</strong></p><p>Implementing:</p><pre>typealias Strings = [String]</pre><p>lets you declare variables -for instance- of type Array of Strings ([String]) as follows:</p><pre>var strs: Strings?</pre><p>Now strs would be a variable of type [String] .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*MJV2Y_n3KTidK48lKool9A.jpeg" /></figure><p>Pretty interesting! Honestly, for me I don’t think so. If you were thinking of “so far, it is useless”, I would kind of agree that 😅.</p><p>There is no doubt that creating a typealias for such a case would not be that useful, in some cases, declaring it as var strs: [String]? would be even better to read… Just calm it down, let’s try another one: what about declaring a typealias for a Dictionary of Strings as keys and Integers for values:</p><pre>typealias CustomDict = Dictionary&lt;String, Int&gt;</pre><p>that should save some “effort” when it comes to declare the concrete types of the generic parameters for the Dictionary (&lt;String, Int&gt;), it is like “bilateral 2 in 1 saving”! However, still not that good reason for using typealias, right? That leads to:</p><h4>Why to use typealias?</h4><p>As a real case, usually when working with a non-trivial app, it should has its own <em>managers</em> for handling tasks for a specified functionality, such as sending and receiving data over a network connection, fetching the device photos (accessing system resources), writing and reading data from/into the disk and so on… Thus implementing these managers might require “pretty long” signatures for their methods. Let’s take one step further and do some code for more “real world” case:</p><p><strong>Example:</strong></p><p><em>To make it more straightforward, I’ll focus on the signatures of the methods, regardless of what are the actual inner implementation of them (the manager purpose).</em></p><p>Consider that we have MyManager which includes foo<strong> </strong>and<strong> </strong>bar<strong> </strong>methods as follows:</p><pre>class MyManager {<br>    //...<br><br>    func foo(success: (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -&gt; (), failure: (_ error: Error, _ message: String, _ workaround: AnyObject) -&gt; ()) {<br>        if isSuccess {<br>            success(..., ..., ..., ...)<br>        } else {<br>            failure(..., ..., ...)<br>        }<br>    }<br><br>    func bar(success: (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -&gt; (), failure: (_ error: Error, _ message: String, _ workaround: AnyObject) -&gt; ()) {<br>        if isSuccess {<br>            success(..., ..., ..., ...)<br>        } else {<br>            failure(..., ..., ...)<br>        }<br>    }<br><br>    // ...<br>}</pre><p>So far so good, but wait a second… these method signatures looks really tedious! both of them take success and failure parameters, and I bet you noticed that they are the same for both of methods:</p><pre>success: (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -&gt; ()</pre><p>and</p><pre>failure: (_ error: Error, _ message: String, _ workaround: AnyObject) -&gt; ()</pre><blockquote>As aside bar note, in your real app, you might need to declare these closures as <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID546">Escaping Closures</a>…</blockquote><p>which could end up with a confusing signature to be read…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*r1AQRMo1hvd3ifYzuHYDwA.jpeg" /></figure><p>Based on our case, when it comes to work with <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html"><em>compound types</em></a><em>,</em> you would definitely notice the benefits of declaring typealiases.</p><p>Typealias is here to save you! So yes, you could let these closure signatures to be typealiases:</p><pre>typealias Success = (_ data: Data, _ message: String, _ status: Int, _ isEnabled: Bool) -&gt; ()</pre><pre>typealias Failure = (_ error: Error, _ message: String, _ workaround: AnyObject) -&gt; ()</pre><p>Thus:</p><pre>class MyManager {<br>    //...<br><br>    func foo(success: Success, failure: Failure) {<br>        if isSuccess {<br>            success(..., ..., ..., ...)<br>        } else {<br>            failure(..., ..., ...)<br>        }<br>    }<br><br>    func bar(success: Success, failure: Failure) {<br>        if isSuccess {<br>            success(..., ..., ..., ...)<br>        } else {<br>            failure(..., ..., ...)<br>        }<br>    }<br><br>    // ...<br>}</pre><p>Much better! At this point it should be more expressive and readable.</p><p>Also from the “reusability” point of view, for implementing similar functions, it would be much easier to use the typealias instead of keeping “copy-paste” the parameters; Editing the declaration of the typealias would be reflected on all the manager method signatures.</p><h4>Wrapping Up:</h4><p>Typealiases are useful, even Swift itself uses them, as a pretty example <a href="https://developer.apple.com/documentation/swift/codable">Codable</a> is a typealias for both <a href="https://developer.apple.com/documentation/swift/decodable">Decodable</a> and <a href="https://developer.apple.com/documentation/swift/encodable">Encodable</a> protocols. However, keep in mind that you should not overuse them, sometimes it would be unnecessary to declare such a typealias (typealias Strings = [String] 😄), just do it when you believe that it is useful.</p><h4><strong>Reference:</strong></h4><ul><li>The Swift Programming Language (Language Reference — Declarations): <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID361">Type Alias Declaration</a>.</li></ul><h4>Author ✍️</h4><p>Appreciate your feedback 👏 Stay tuned for more “Swift, more elegant code” topics.</p><p>Thanks for Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e6d59f07f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>