<?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[The Mobile Stack - Medium]]></title>
        <description><![CDATA[“The Mobile Stack” explores the coding, tools, frameworks, and strategies shaping modern mobile development. From cross-platform solutions to native app optimization, it delivers concise, actionable insights to help developers build the future of mobile experiences. - Medium]]></description>
        <link>https://medium.com/the-mobile-stack?source=rss----e72cc1d2e5fd---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Mobile Stack - Medium</title>
            <link>https://medium.com/the-mobile-stack?source=rss----e72cc1d2e5fd---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:11:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-mobile-stack" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A comprehensive guide to TensorFlow Lite (TFLite) and its usage in mobile apps.]]></title>
            <link>https://medium.com/the-mobile-stack/flutter-tensor-flow-lite-i-a577bd7b5492?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/a577bd7b5492</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 14:16:15 GMT</pubDate>
            <atom:updated>2025-02-15T14:16:15.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bJqTCP5EQH3nl2Ea" /><figcaption>Photo by <a href="https://unsplash.com/@tomspentys?utm_source=medium&amp;utm_medium=referral">Tom Claes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artificial Intelligence (AI) is changing mobile applications, e.g., from the background recognition of an object in an image to the speech recognition. However, there are drawbacks to running AI models on mobile devices:.</p><ul><li>Limited processing power.</li><li>Battery consumption.</li><li>Model size constraints.</li></ul><p>Enter <a href="https://www.tensorflow.org/"><strong>TensorFlow Lite (TFLite)</strong></a> Google’s lean, mean, and optimized inference framework for deploying machine learning models on mobile and edge devices.</p><h3>What is TensorFlow Lite?</h3><p><strong>TensorFlow Lite (TFLite)</strong> is a mobile-enabled version of TensorFlow, which can be used to execute ML models effectively on:</p><ul><li>Android &amp; iOS</li><li>Edge devices (Raspberry Pi, microcontrollers, etc.)</li><li>Embedded systems (IoT devices, smart cameras, etc.)</li></ul><p><strong>TFLite</strong> is optimized for low-latency and high-throughput inference, ie, models can be deployed on mobile devices without an online cloud connection.</p><h3>How does TensorFlow Lite work?</h3><h4>Step 1: Train a model</h4><p>Models are usually trained on a powerful machine (GPU/TPU) using <strong>TensorFlow</strong>.</p><h4>Step 2: Convert to TFLite format</h4><p>After the model is trained, it has been converted to the <em>.tflite</em> file format via the <em>TensorFlow Lite Converter</em>.</p><h4>Step 3: Deploy on a mobile app</h4><p>The <em>.tflite</em> model is loaded into an android/iOS mobile app, and is run inside the mobile app by TFLite Interpreter.</p><h4>Step 4: Perform inference</h4><p>The application decodes inputs (such as images, text, or audio) and feeds them to the model to obtain prediction.</p><h3>Why use TensorFlow Lite?</h3><ul><li><strong>Optimized for mobile</strong>: Work well on CPU, GPU, and Neural Processing Unit (NPU).</li><li><strong>Low latency</strong>: No internet connection needed — everything runs locally.</li><li><strong>Smaller model size</strong>: Reduces the model’s footprint for mobile devices.</li><li><strong>Battery-efficient</strong>: Uses fewer resources compared to cloud-based inference.</li></ul><h3>How to use TensorFlow Lite in a Flutter app?</h3><p>Let’s integrate <strong>TFLite</strong> into a Flutter app to classify images.</p><h4>Step 1: Install dependencies</h4><p>Run the following command: Run the following command:</p><pre>flutter pub add tflite</pre><h4>Step 2: Add the TFLite model</h4><p>In the case of <em>trained.tflite</em> model and <em>labels.txt</em>, place them within the <em>assets/ folder</em>.</p><pre>assets/<br>├── model.tflite<br>├── labels.txt</pre><p>Then, declare them in <em>pubspec.yaml</em>:</p><pre>flutter:<br>  assets:<br>    - assets/model.tflite<br>    - assets/labels.txt</pre><h4>Step 3: Load the model</h4><p>Create a <em>TFLiteService</em> class inside <em>lib/services/tflite_service.dart</em>:</p><pre>import &#39;package:tflite/tflite.dart&#39;;<br><br>class TFLiteService {<br>  static Future&lt;void&gt; loadModel() async {<br>    await Tflite.loadModel(<br>      model: &quot;assets/model.tflite&quot;,<br>      labels: &quot;assets/labels.txt&quot;,<br>    );<br>  }<br><br>  static Future&lt;List?&gt; classifyImage(String imagePath) async {<br>    return await Tflite.runModelOnImage(<br>      path: imagePath,<br>      numResults: 3,<br>      threshold: 0.5,<br>    );<br>  }<br><br>  static void dispose() {<br>    Tflite.close();<br>  }<br>}</pre><p>What’s happening here?</p><ul><li><strong>loadModel()</strong>: Loads the <em>.tflite</em> model and labels.</li><li><strong>classifyImage(imagePath)</strong>: Runs image classification.</li><li><strong>dispose()</strong>: Frees up memory when done.</li></ul><h4>Step 4: Select an image</h4><p>We’ll allow users to pick an image using the <em>image_picker</em> package.</p><pre>flutter pub add image_picker</pre><p>Modify <em>main.dart</em>:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:image_picker/image_picker.dart&#39;;<br>import &#39;services/tflite_service.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await TFLiteService.loadModel();<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: ImageClassifierScreen(),<br>    );<br>  }<br>}<br><br>class ImageClassifierScreen extends StatefulWidget {<br>  @override<br>  _ImageClassifierScreenState createState() =&gt; _ImageClassifierScreenState();<br>}<br><br>class _ImageClassifierScreenState extends State&lt;ImageClassifierScreen&gt; {<br>  String? _imagePath;<br>  List? _predictions;<br><br>  Future&lt;void&gt; _pickImage() async {<br>    final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);<br>    if (pickedFile == null) return;<br><br>    setState(() {<br>      _imagePath = pickedFile.path;<br>    });<br><br>    final results = await TFLiteService.classifyImage(_imagePath!);<br>    setState(() {<br>      _predictions = results;<br>    });<br>  }<br><br>  @override<br>  void dispose() {<br>    TFLiteService.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;TFLite Image Classifier&quot;)),<br>      body: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: [<br>          _imagePath != null<br>              ? Image.file(File(_imagePath!))<br>              : const Icon(Icons.image, size: 100),<br>          const SizedBox(height: 20),<br>          ElevatedButton(<br>            onPressed: _pickImage,<br>            child: const Text(&quot;Pick Image&quot;),<br>          ),<br>          const SizedBox(height: 20),<br>          _predictions != null<br>              ? Column(<br>                  children: _predictions!.map((result) {<br>                    return Text(<br>                      &quot;${result[&#39;label&#39;]} - ${(result[&#39;confidence&#39;] * 100).toStringAsFixed(2)}%&quot;,<br>                      style: const TextStyle(fontSize: 18),<br>                    );<br>                  }).toList(),<br>                )<br>              : const Text(&quot;Select an image to classify&quot;),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h4>Running the App</h4><p>Start the app:</p><pre>flutter run</pre><p><strong>How it works</strong></p><ul><li>User selects an image.</li><li>Image is passed to <em>TFLiteService.classifyImage()</em>.</li><li>The app shows classification results (e.g., “Dog — 97.5%).</li></ul><h3>What’s next?</h3><ul><li>Use real-time camera input instead of static images.</li><li>Optimize models to run even faster.</li><li>Train a custom model using <a href="https://teachablemachine.withgoogle.com/"><em>Google’s Teachable Machine</em></a>.</li></ul><p><strong>TFLite</strong> makes AI-powered mobile apps fast, efficient, and powerful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a577bd7b5492" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/flutter-tensor-flow-lite-i-a577bd7b5492">A comprehensive guide to TensorFlow Lite (TFLite) and its usage in mobile apps.</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement OCR in Your Flutter App (Updated)]]></title>
            <link>https://medium.com/the-mobile-stack/how-to-implement-ocr-in-your-flutter-app-updated-f9a0c5fcf764?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/f9a0c5fcf764</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[ocr-software]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 13:31:10 GMT</pubDate>
            <atom:updated>2025-02-15T13:30:28.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bXoPLmMEyVAoqE65VhHAw.jpeg" /><figcaption>Image by the author</figcaption></figure><h3>Introduction</h3><p>Think of capturing a document, sign, or handwritten note with a set camera view and receiving the text immediately. That’s the magic of <em>Optical Character Recognition (OCR)</em>.</p><p>Integrating OCR into your Flutter app can significantly enhance user experience, enabling functionalities like digitizing printed text or automating data entry. In this guide, we’ll explore how to implement OCR in a Flutter application using up-to-date packages and best practices.</p><h3>Step 1: Selecting the appropriate OCR package</h3><p>Flutter offers several packages to facilitate OCR capabilities. Here are some notable options:</p><ul><li><a href="https://pub.dev/packages/ocr_scan_text"><strong>ocr_scan_text</strong></a>: A wrapper around Google’s ML Kit Text Recognition library providing the capability to accurately extract text from images or PDFs.</li><li><a href="https://pub.dev/packages/flutter_tesseract_ocr"><strong>flutter_tesseract_ocr</strong></a>: Applies the Tesseract 4 engine, which is based on over 100 languages using network-based OCR engine with line-based recognition.</li><li><a href="https://pub.dev/packages/flutter_vision_ocr"><strong>flutter_vision_ocr</strong></a>: Offers OCR capabilities based on the Vision API and allows text extraction from images as well as, real-time recognition from the camera of the device.</li></ul><p>For this tutorial, we’ll use <strong>ocr_scan_text</strong> due to its ease of integration and robust performance.</p><h3>Step 2: Adding dependencies</h3><p>Update your <em>pubspec.yaml</em> file to include the necessary dependencies (updated):</p><pre>dependencies:<br>    flutter: flutter:<br>        sdk: flutter<br>    ocr_scan_text: ^1.3.1<br>    image_picker: ^1.1.2<br>    permission_handler: ^11.3.1</pre><ul><li><strong>ocr_scan_text</strong>: Facilitates text recognition.</li><li><strong>image_picker</strong>: Enables image selection from the gallery or camera.</li><li><strong>permission_handler</strong>: Manages runtime permissions. After updating, run:</li></ul><h3>Step 3: Configuring permissions</h3><p>Make sure that your application also has permissions for using the camera and storage:</p><p><strong>For Android</strong>: Add the following to your <em>AndroidManifest.xml</em>:</p><pre>&lt;uses-permission android: name=&quot;android.permission.CAMERA&quot; /&gt;<br>&lt;uses-permission android: name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;<br>&lt;uses-permission android: name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;</pre><pre>&lt;application&gt; &lt;!-- Other configurations --&gt;<br>    &lt;activity android: name=&quot;com.google.mlkit.vision.text.TextRecognitionActivity&quot; /&gt;<br>&lt;/application&gt;</pre><p><strong>For iOS</strong>: Update your <em>Info.plist</em>:</p><pre>&lt;key&gt;NSCameraUsageDescription&lt;/key&gt;<br>&lt;string&gt;We need access to your camera for text recognition.&lt;/string&gt;<br>&lt;key&gt;NSPhotoLibraryUsageDescription&lt;/key&gt;<br>&lt;text&gt;Access to your photo library is required for text recognition&lt;/text&gt;.</pre><h3>Step 4: Requesting permissions at runtime</h3><p>Before requesting the camera or gallery access, get permission as follows:</p><pre>import &#39;package:permission_handler/permission_handler.dart&#39;;</pre><pre>Future&lt;void&gt; requestPermissions() async {<br>  await [<br>    Permission.camera,<br>    Permission.storage,<br>  ].request();<br>}</pre><p>Invoke <em>requestPermissions()</em> at an appropriate point in your app, such as during initialization or before accessing the camera. ## Step 5: Capturing or Selecting an Image Grant users the ability to take a new photo, or choose from their gallery:</p><h3>Step 5: Capturing or selecting an image</h3><p>Grant users the ability to take a new photo, or choose from their gallery:</p><pre>import &#39;package:image_picker/image_picker.dart&#39;;<br>import &#39;dart:io&#39;;<br><br>Future&lt;File?&gt; pickImage(ImageSource source) async {<br>  final picker = ImagePicker();<br>  final pickedFile = await picker.pickImage(source: source);<br>  return pickedFile != null ? File(pickedFile.path) : null;<br>}</pre><p>Usage:</p><pre>File? image = await pickImage(ImageSource.camera); // or ImageSource.gallery</pre><h3>Step 6: Extracting Text from the Image</h3><p>Utilize the <em>ocr_scan_text</em> package to process the image and extract text:</p><pre>import &#39;package:ocr_scan_text/ocr_scan_text.dart&#39;;<br>import &#39;dart:io&#39;;<br><br>Future&lt;String&gt; extractText(File imageFile) async {<br>  final ocrText = await OcrScanText.recognize(imageFile.path);<br>  return ocrText;<br>}</pre><h3>Step 7: Integrating into the UI</h3><p>Combine the functionalities into a Flutter widget:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;dart:io&#39;;<br><br>class OCRScreen extends StatefulWidget {<br>  @override<br>  _OCRScreenState createState() =&gt; _OCRScreenState();<br>}<br><br>class _OCRScreenState extends State&lt;OCRScreen&gt; {<br>  File? _image;<br>  String _extractedText = &quot;&quot;;<br><br>  Future&lt;void&gt; _pickAndExtractText(ImageSource source) async {<br>    final image = await pickImage(source);<br>    if (image == null) return;<br>    setState(() {<br>      _image = image;<br>    });<br>    final text = await extractText(image);<br>    setState(() {<br>      _extractedText = text;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;OCR Demo&#39;)),<br>      body: SingleChildScrollView(<br>        child: Column(<br>          children: [<br>            if (_image != null) Image.file(_image!),<br>            ElevatedButton(<br>              onPressed: () =&gt; _pickAndExtractText(ImageSource.camera),<br>              child: Text(&quot;Capture Image&quot;),<br>            ),<br>            ElevatedButton(<br>              onPressed: () =&gt; _pickAndExtractText(ImageSource.gallery),<br>              child: Text(&quot;Pick from Gallery&quot;),<br>            ),<br>            Padding(<br>              padding: const EdgeInsets.all(16.0),<br>              child: Text(_extractedText),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Step 8: Testing and Optimization</h3><p>Test the OCR functionality with various text types:</p><ul><li><strong>Printed text</strong>: Should yield high accuracy.</li><li><strong>Handwritten text</strong>: Accuracy may vary; consider using models specialized for handwriting.</li><li><strong>Different languages</strong>: Ensure the OCR engine supports the desired language.</li></ul><p>For improved accuracy:</p><ul><li>Use high-quality images with clear text.</li><li>Ensure proper lighting conditions during image capture.</li><li>Preprocess images (e.g., adjusting contrast) before text extraction.</li></ul><h3>Conclusion</h3><p>Adding OCR capabilities to your Flutter application augments the app’s ability to interact with the real world by converting text off of images to plain text.</p><p>By following this guide, you can implement a robust OCR feature, providing users with a seamless and efficient text extraction experience. Just take your time to try various OCR packages and parameters to see which are suitable to your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9a0c5fcf764" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/how-to-implement-ocr-in-your-flutter-app-updated-f9a0c5fcf764">How to Implement OCR in Your Flutter App (Updated)</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Master Swift Optionals]]></title>
            <link>https://medium.com/the-mobile-stack/how-to-master-swift-optionals-6e45bb05a023?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/6e45bb05a023</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 09:09:26 GMT</pubDate>
            <atom:updated>2025-01-25T15:55:11.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>Safeguard your code with Swift optional handling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x0otJytp4pmHCHQm" /><figcaption>Photo by <a href="https://unsplash.com/@emilymorter?utm_source=medium&amp;utm_medium=referral">Emily Morter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p><strong>“Unexpectedly found nil while unwrapping an Optional value.”</strong></p><p>This issue arises when handling data that might be absent — a scenario common in app development, where APIs, user inputs, and database queries often return uncertain results.</p><p>Managing these situations effectively can mean the difference between a robust application and a crash-prone nightmare.</p><h3>Why Swift <strong>Optionals</strong>?</h3><p><strong>Swift optionals</strong> offer a great capability to handle the <em>presence or absence of values safely</em>.<strong> Swift optionals</strong> are defined as a core feature of the language and they eliminate most of the potential causes of runtime errors by forcing developers to formally document nil values.</p><p>Swift 6 further refines this lineage through natural and efficient extensions of Optionals, as opposed to coincidences.</p><h3>Overview of Swift optionals</h3><h4>Definition and main purpose</h4><p>A <strong>Swift optional</strong> is a data type that can be an instance of either a value or <strong>nil</strong>, signifying that the data is missing. Declared with <strong>symbol ?</strong>, optionals help developers write safer code by making <strong>nil</strong>-handling explicit.</p><pre>var name: String? = nil // This variable may hold a String or nil.</pre><h4>Key features and benefits</h4><ul><li><strong>Type safety.</strong> Forces explicit handling of nil values.</li><li><strong>Unwrapping mechanisms.</strong> Provides multiple ways to safely access the wrapped value.</li><li><strong>Improved debugging.</strong> Clearly indicates when a value is <strong>nil</strong>.</li></ul><h4>Important concepts</h4><ul><li><strong>Optional binding.</strong> Safe unwrapping of optionals by using <em>if let </em>or <em>guard let</em>.</li><li><strong>Optional chaining.</strong> Accessing properties, methods, and subscripts on an optional.</li><li><strong>Nil-coalescing operator.</strong> Providing a default value using <strong>??</strong>.</li><li><strong>Implicitly unwrapped optionals.</strong> Declared with <strong>!</strong> and used sparingly for guaranteed values.</li></ul><h3>Implementation guide</h3><h4>Basic setup</h4><p>Begin a new Xcode project or use Swift Playground session for rapid iteration. Define a few variables to explore optional concepts:</p><pre>var optionalString: String? = &quot;Hello, Swift!&quot;<br>var optionalInt: Int? = nil</pre><h4>Safely unwrapping optionals</h4><p>Using <em>if let</em> binding.</p><pre>if let unwrappedString = optionalString {<br>    print(&quot;Unwrapped value: \(unwrappedString)&quot;)<br>} else {<br>    print(&quot;optionalString is nil&quot;)<br>}</pre><p>Using <em>guard let</em> binding.</p><pre>func greet(_ name: String?) {<br>    guard let name = name else {<br>        print(&quot;Name is nil.&quot;)<br>        return<br>    }<br>    print(&quot;Hello, \(name)!&quot;)<br>}<br><br>greet(optionalString) // Output: Hello, Swift!</pre><h4>Optional chaining</h4><p>Access properties and methods on optionals safely:</p><pre>struct Person {<br>    var address: String?<br>}<br><br>let person = Person(address: &quot;123 Swift Lane&quot;)<br>if let address = person.address?.uppercased() {<br>    print(&quot;Address: \(address)&quot;)<br>} else {<br>    print(&quot;Address not available.&quot;)<br>}</pre><h4>Using the nil-coalescing operator</h4><p>Provide a default value when an optional is <strong>nil</strong>:</p><pre>let defaultName = &quot;Anonymous&quot;<br>let username = optionalString ?? defaultName<br>print(&quot;Username: \(username)&quot;)</pre><h4>Advanced optional handling</h4><p><strong>Optional <em>map</em> and <em>flatMap</em></strong></p><p>Transform and chain operations on optionals</p><p><strong>map</strong></p><pre>// Single optional value<br>let optionalNumber: Int? = 45<br>let result = optionalNumber.map { $0 * 2 } // Doubles the value if not nil<br>print(&quot;Result: \(result ?? 0)&quot;) // Result: 90<br><br>// Array of optionals<br>let optionalNumbers: [Int?] = [45, nil]<br>let results = optionalNumbers.map { $0 ?? 0 * 2 } // Handle nil with default value<br>print(&quot;Results: \(results)&quot;) // Results: [45, 0]</pre><p><strong>flatMap</strong></p><pre>// Single optional value with flatMap<br>let optionalNumber: Int? = 45<br>let flatMapResult = optionalNumber.flatMap { value in<br> // This closure can transform and potentially return another optional<br> if value &gt; 40 {<br>  return value * 2<br> }<br> return nil<br>}<br>print(&quot;FlatMap Result: \(flatMapResult ?? 0)&quot;) // Result: 90<br><br><br>let optionalNumberArray: [Int?] = [45, nil, 80, 20]<br>let flatMapArrayResult = optionalNumberArray.flatMap { value -&gt; [Int] in<br> // Safely unwrap the optional and apply the transformation<br> guard let unwrappedValue = value, unwrappedValue &gt; 40 else { return [] }<br> return [unwrappedValue * 2]<br>}<br>print(&quot;FlatMap Result: \(flatMapArrayResult)&quot;) // Result: [90, 160]// Result: 90</pre><h3>Important technical considerations</h3><h4>Key architectural decisions</h4><ul><li><strong>Use optionals judiciously.</strong> Avoid using optionals for values that are always expected to be non-nil.</li><li><strong>Define clear contracts. </strong>Use non-optional types wherever possible to reduce ambiguity.</li></ul><h4>Error handling</h4><ul><li>Combine optionals with error handling for robust code:</li></ul><pre>func fetchData(from url: String) throws -&gt; String? {<br>    guard !url.isEmpty else { throw URLError(.badURL) }<br>    return &quot;Sample Data&quot;<br>}<br><br>do {<br>    let data = try fetchData(from: &quot;&quot;) ?? &quot;Default Data&quot;<br>    print(data)<br>} catch {<br>    print(&quot;Error: \(error)&quot;)<br>}</pre><h4>Common issues and solutions</h4><ul><li><strong>Force unwrapping.</strong> Avoid using <strong>!</strong> (<em>force unwrapping</em>) unless absolutely sure the value is not <strong>nil</strong>.</li><li><strong>Implicit optionals.</strong> Use sparingly and document their behavior clearly.</li></ul><h4>Best practices</h4><ul><li>Default values: Use <strong>nil-coalescing</strong> to simplify code.</li><li><strong>Avoid Pyramid of Doom.</strong> Use <em>guard let</em> to flatten nested unwrapping.</li><li><strong>Document assumptions.</strong> Detail the condition under which a value is <strong>nil</strong> and outlining why.</li></ul><h3>Conclusion</h3><p><strong>Swift optionals</strong> allow to write safer and more effective code. Knowing the purpose of the objects as well as the presence and types of features such as <strong>unwrapping</strong>, <strong>nil-coalescing</strong> and <strong>optional chaining</strong>, allows to manage uncertainty on any sort of nil value.</p><blockquote>Liking this? Follow <a href="https://medium.com/u/96dd69cf281">Raúl Ferrer</a> on Medium (and, better, <a href="https://raulferrer.medium.com/subscribe"><strong>subscribe me</strong></a>) for more insights and inspiration!</blockquote><p>And remember to<strong> subscribe my newsletter</strong> for insightful content about code, lead and grow.</p><p><a href="https://codeleadgrow.substack.com/">Code, Lead, Grow | Raúl Ferrer | Substack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e45bb05a023" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/how-to-master-swift-optionals-6e45bb05a023">How to Master Swift Optionals</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Master Null Safety in Dart]]></title>
            <link>https://medium.com/the-mobile-stack/how-to-master-dart-null-safety-0d289c04fcd2?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/0d289c04fcd2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 15:12:20 GMT</pubDate>
            <atom:updated>2025-01-12T15:12:20.493Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to eliminate null errors in Dart with null safety.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0OXrr5Mbk0uQpQe9" /><figcaption>Photo by <a href="https://unsplash.com/@chrumo?utm_source=medium&amp;utm_medium=referral">Piotr Chrobot</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Null safety</strong> is the most effective feature in <strong>Dart</strong>, which is intended to eradicates <strong>null</strong> reference corruption (better known as the “billion-dollar bug”.</p><p>Becoming strong in <strong>null safety</strong> enables your <strong>Dart</strong> applications to be robust, manageable and contribute negligible amounts of runtime exceptions.</p><p>This guide will teach you the whole, and in turn how to use the whole, null safety and how to use it correctly throughout your dart applications.</p><h3>What is null safety?</h3><p><strong>Null safety</strong> is the process by which guarantees in <strong>Dart</strong> that a <em>non-nullable</em> <em>variable</em> cannot be written a <em>null value</em> are enforced. This functionality was also introduced in <strong>Dart 2.12</strong> and is now actually embedded in the language.</p><p>With <strong>null safety</strong>:</p><ul><li>Variables are <strong>non-null</strong> by default, i.e., variables should not be <strong>null</strong> unless explicitly marked as nullable.</li><li>Computationally possible <strong>null</strong> errors are detected at compile time, i.e., prior to runtime, and thus safer code is produced.</li></ul><h3>Why is null safety important?</h3><ul><li><strong>Prevents runtime errors.</strong> <strong>Null</strong> safety pins null-related issues at compile time, thus increases the application less crash in run time.</li><li><strong>Improves code quality.</strong> Explicit nullability declarations, on the other hand, are readable and maintainable code.</li><li><strong>Boosts developer productivity.</strong> Early error detection is a mechanism that minimizes effort for debugging and can be exploited to steer effort towards the development of new features.</li><li><strong>Ensures compatibility.</strong> Modern <strong>Flutter</strong> and <strong>Dart</strong> libraries are based on null safety, and your code needs to be null-safe in order to use the newest tooling.</li></ul><h3>How null safety works in Dart</h3><h4>Non-nullable variables by default</h4><p>In null-safe <strong>Dart</strong>, variables are non-nullable by default. In other words, every variable must be a valid, non-null statement.</p><p><strong>Example:</strong></p><pre>int age 30; // Non-nullable, must always have a value.<br>age = null; // Compile-time error: null is not allowed.</pre><h4>Nullable variables</h4><p>If a variable can take a null value, declare it as nullable by adding a? after the type.</p><p><strong>Example:</strong></p><pre>int? age; // Nullable, can hold null.<br>age = null; // Allowed.</pre><h4>Null assertion operator (!)</h4><p>The <strong>null assertion operator</strong> tells <strong>Dart</strong> that a nullable variable is no longer null. Use with caution, as it may lead to the runtime error by null variable.</p><p><strong>Example:</strong></p><pre>int? age = 30;<br>int myAge = age! ; // Asserts that age is not null.</pre><h4>The late keyword</h4><p>The <strong>late</strong> keyword delays the initialization of a <strong>non-nullable</strong> type variable until it is actually used. And not only to the case of data computed after the constructor and even during the runtime.</p><p><strong>Example:</strong></p><pre>late String username;<br>username = &#39;John Doe&#39;; // Initialized later.<br>print(username); // Output: John Doe.</pre><h4>Null-aware operators</h4><p><strong>Dart</strong> provides several <em>null-aware</em> operators to simplify the handling of nullable values:</p><ul><li><strong>?? (default value).</strong> The value is returned if it is not <strong>null</strong> and provides a default one if it is.</li></ul><pre>int? age;<br>print(age ?? 18); // Output: 18.</pre><ul><li><strong>?. (conditional member access).</strong> Does not invoke a method or access a property unless an object is <strong>not</strong> <strong>null</strong>.</li></ul><pre>String? name;<br>print(name?.toUpperCase()); // Output: null.</pre><ul><li><strong>??= (assign if null).</strong> Assigns a value only if the variable is <strong>null</strong>.</li></ul><pre>int? age;<br>age ? ?= 25; // Assigns 25 if age is null.</pre><h3>Step-by-step guide to master null safety</h3><h4>Enable null safety in your project</h4><p>If you’re upgrading an older <strong>Dart</strong> project (older than Dart 2.12 version), enable null safety by updating the Dart SDK to version 2.12 or later and migrating your code.</p><h4>Handle null values gracefully</h4><p>For performance, make use of <strong>null-aware operators</strong> and optional chaining to safely perform operations on possibly <strong>null</strong> values. Avoid overusing the <strong>null assertion operator (!)</strong>, as it can lead to runtime errors.</p><h4>Test your null safety implementation</h4><p>Thorough testing ensures your <strong>null-safety</strong> implementation works as expected. Use <strong>Dart</strong>’s built-in testing framework to verify your changes:</p><pre>dart test</pre><h4>Practice with real-world examples</h4><p>Add null safety for typical scenarios such as use of APIs, databases, and UI.</p><p><strong>Example:</strong></p><pre>Future&lt;String?&gt; fetchUserName() async {<br>  // Simulates an API call that may return null.<br>  return null;<br>}<br><br>void main() async {<br>  String? name = await fetchUserName();<br>  print(name ?? &#39;Guest&#39;); // Output: Guest.<br>}</pre><h3>Common pitfalls and how to avoid them</h3><p><strong>Overusing the null assertion operator (!)</strong></p><ul><li><strong>Problem.</strong> Leads to runtime errors if the variable is null.</li><li><strong>Solution.</strong> Use null-aware operators or check for null explicitly.</li></ul><p><strong>Ignoring late initialization</strong></p><ul><li><strong>Problem.</strong> If the following of an object variable declared in a late variable before its initialization is used, it will throw a runtime error.</li><li><strong>Solution.</strong> Ensure late variables are initialized before use.</li></ul><p><strong>Neglecting testing</strong></p><ul><li><strong>Problem.</strong> Missed null safety issues can lead to crashes.</li><li><strong>Solution.</strong> Write comprehensive tests to cover edge cases.</li></ul><h3><strong>Conclusion</strong></h3><p><strong>Null safety</strong> is one of the main aspects that make for safer and more stable code in <strong>Dart</strong>. By learning <strong>null safety</strong> concepts, collaborating with <strong>null-aware operators</strong>, and prototyping on real-world examples, you will be ready to master this functionality and significantly improve the performance of your <strong>Dart</strong> projects.</p><p>Start applying <strong>null safety</strong> in your projects today to take full advantage of <strong>Dart</strong>’s capabilities. <strong>Null safety</strong> should be your guide to the creation of error-free, maintainable software.</p><blockquote>Liking this? Follow <a href="https://medium.com/u/96dd69cf281">Raúl Ferrer</a> on Medium (and, better, <a href="https://raulferrer.medium.com/subscribe"><strong>subscribe me</strong></a>) for more insights and inspiration!</blockquote><p>And remember to<strong> subscribe my newsletter</strong> for insightful content about code, lead and grow.</p><p><a href="https://codeleadgrow.substack.com/">Code, Lead, Grow | Raúl Ferrer | Substack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d289c04fcd2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/how-to-master-dart-null-safety-0d289c04fcd2">How to Master Null Safety in Dart</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Principles for Writing Clean Code in Dart]]></title>
            <link>https://medium.com/the-mobile-stack/10-principles-for-writing-clean-code-in-dart-3a75be8b2745?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/3a75be8b2745</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[flutter-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 15:57:27 GMT</pubDate>
            <atom:updated>2025-01-11T15:57:27.819Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make code cleaner, more readable, and more efficient with these principles for mastering Dart.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMoWV15iIgU70UMJIkeQgA.jpeg" /><figcaption>Image created by the author with Ideogram.ai.</figcaption></figure><p><strong>Clean code isn’t about perfection; it’s about communication.</strong> It’s like writing it just for later you (or your team), so that it says, “Here’s what I’d invented”. <strong>Dart</strong>, with its elegant syntax and rich set of capabilities, can be used as a programming language for elegant code.</p><p>Whether you’re building <strong>Flutter</strong> apps or backend services, these principles will make your code a joy to write, read, and maintain.</p><p>Okay, let’s explore the craft of writing clean Dart, code with practical examples, tips, and a touch of humor.</p><h3>1. Keep your methods short and sweet</h3><p><strong>Rule of thumb:</strong> There should be a method with a single purpose which performs that purpose adequately.</p><p>Imagine walking into a kitchen to bake a cake. Luckily, you do not want to stumble onto a recipe that goes along with renovation tips for the kitchen. Keep your methods focused.</p><p>For example, instead of this:</p><pre>void processUserData(User user) {  <br>  validateUser(user);  <br>  saveToDatabase(user);  <br>  sendWelcomeEmail(user);  <br>}</pre><p>Do this:</p><pre>void processUserData(User user) {  <br>  if (_isValidUser(user)) {  <br>    _saveUser(user);  <br>    _sendWelcomeEmail(user);  <br>  }  <br>}  <br><br>bool _isValidUser(User user) {  <br>  // Validation logic  <br>}  <br><br>void _saveUser(User user) {  <br>  // Database save logic  <br>}  <br><br>void _sendWelcomeEmail(User user) {  <br>  // Email logic  <br>}</pre><p><em>Shorter methods make testing easier and debugging faster.</em></p><h3>2. Name things like a pro</h3><p><strong>Clear is better than clever.</strong></p><p>Your code shouldn’t feel like solving a crossword puzzle. Variables, classes, and methods should have names indicating their purpose.</p><p>Avoid this:</p><pre>int x = calculate(a, b);</pre><p>Go for this:</p><pre>int totalCost = calculateCost(basePrice, tax);</pre><p><em>Readable code is maintainable code.</em></p><h3>3. Use Dart’s Null safety like a boss</h3><p><strong>Dart</strong>’s null safety is a gift, not a chore. Use it to avoid those annoying runtime crashes.</p><p>Instead of sprinkling <strong>!</strong> everywhere like confetti:</p><pre>String getUserName(User? user) {  <br>  return user!.name;  <br>}</pre><p>Be deliberate:</p><pre>String getUserName(User? user) {  <br>  return user?.name ?? &#39;Guest&#39;;  <br>}</pre><p>Default values save lives (and debugging hours).</p><p><a href="https://levelup.gitconnected.com/mastering-the-null-aware-operator-in-dart-the-power-of-and-37fbf2dcd2d8">Mastering the Null-Aware Operator in Dart: The Power of ?? and ??=</a></p><h3>4. Embrace Dart’s built-in features</h3><p><strong>Dart</strong> is full of features that are rather easy to code. Use them.</p><p>For example, collection <em>If</em> and <em>Spread Operators</em></p><p>Why write this:</p><pre>List&lt;String&gt; getShoppingList(bool includeSnacks) {  <br>  List&lt;String&gt; list = [&#39;Bread&#39;, &#39;Milk&#39;];  <br>  if (includeSnacks) {  <br>    list.add(&#39;Chips&#39;);  <br>  }  <br>  return list;  <br>}</pre><p>When you can do this:</p><pre>List&lt;String&gt; getShoppingList(bool includeSnacks) =&gt; [&#39;Bread&#39;, &#39;Milk&#39;, if (includeSnacks) &#39;Chips&#39;];</pre><p>Cleaner, shorter, and more expressive.</p><p><a href="https://levelup.gitconnected.com/darts-spread-operator-the-secret-weapon-for-clean-flutter-code-5b82864c90a8">Dart’s Spread Operator: The Secret Weapon for Clean Flutter Code</a></p><h3>5. Comment with purpose</h3><p>Write comments to clarify, not to narrate.</p><p>Bad comments:</p><pre>// Increment i by 1<br>i++;</pre><p>Good comments:</p><pre>// Adjust index to account for zero-based array<br>i++;</pre><p><em>Write code that doesn’t need comments, but when you do, make them meaningful.</em></p><h3>6. Follow a consistent formatting style</h3><p><strong>Formatting isn’t just about aesthetics; it’s about readability.</strong> Use<strong> Dart</strong>’s dart format tool religiously.</p><p>For example, instead of this chaos:</p><pre>void main(){print(&#39;Hello, World!&#39;);}</pre><p>Follow this:</p><pre>void main() {<br>  print(&#39;Hello, World!&#39;);<br>}</pre><p>Consistency breeds confidence.</p><h3>7. Test early, test often</h3><p><strong>Testing isn’t optional; it’s essential.</strong> Unit tests are very easy to write in the test package of <strong>Dart</strong>.</p><p>Example:</p><pre>import &#39;package:test/test.dart&#39;;  <br><br>void main() {  <br>  test(&#39;calculateCost adds basePrice and tax&#39;, () {  <br>    expect(calculateCost(100, 20), equals(120));  <br>  });  <br>}</pre><p>Every bug you catch in a test prevents you from getting one headache in production.</p><h3>8. Avoid over-engineering</h3><p>Don’t turn a bicycle into a spaceship. Keep your solutions as simple as possible.</p><p>For example, there is no need to use a custom iterator if it can be solved using a <em>for-loop</em>.</p><p>Instead of this:</p><pre>void printNumbers(List&lt;int&gt; numbers) {  <br>  numbers.forEach((number) {  <br>    print(number);  <br>  });  <br>}</pre><p>Just do this:</p><pre>void printNumbers(List&lt;int&gt; numbers) {<br>  for (var number in numbers) {<br>    print(number);<br>  }<br>}</pre><h3>9. Refactor ruthlessly</h3><p><strong>Your first draft is just that — a draft.</strong> Refactor to simplify, optimize, and improve readability.</p><p>For example, before:</p><pre>void showWelcomeMessage(User user) {<br>  if (user.isLoggedIn) {<br>    print(&#39;Welcome ${user.name}!&#39;);<br>  } else {<br>    print(&#39;Please log in.&#39;);<br>  }<br>}</pre><p>After:</p><pre>void showWelcomeMessage(User user) =&gt; print(user.isLoggedIn ? &#39;Welcome ${user.name}!&#39; : &#39;Please log in.&#39;);</pre><h3>10. Think about the future developer</h3><p>Write code as if the next person maintaining it is a tired developer after a long day.</p><p>For example, add meaningful error messages.</p><p>Bad:</p><pre>throw Exception(&#39;Error&#39;);</pre><p>Good:</p><pre>throw Exception(&#39;Invalid user ID: $userId&#39;);</pre><h3>Final thoughts</h3><p><strong>Clean code is a mindset, not a finish line.</strong> It’s a matter of designing solutions both beautiful and effective. <strong>Dart</strong> provides the tools, but it all depends on how you exercise them.</p><p>Start small. Refactor that one messy function. Rename that ambiguous variable. Each step brings you closer to code you can be proud of — and that your future self will thank you for.</p><p>Ultimately, pure <strong>Dart</strong> code is not just a matter of the code itself. It is a question of the pleasure of making something that is well designed to work perfectly and to last.</p><blockquote>Liking this? Follow <a href="https://medium.com/u/96dd69cf281">Raúl Ferrer</a> on Medium (and, better, <a href="https://raulferrer.medium.com/subscribe"><strong>subscribe me</strong></a>) for more insights and inspiration!</blockquote><p><a href="https://codeleadgrow.substack.com/">Code, Lead, Grow | Raúl Ferrer | Substack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a75be8b2745" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/10-principles-for-writing-clean-code-in-dart-3a75be8b2745">10 Principles for Writing Clean Code in Dart</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write for The Mobile Stack: Share Your Expertise in Mobile Development]]></title>
            <link>https://medium.com/the-mobile-stack/write-for-the-mobile-stack-share-your-expertise-in-mobile-development-8b72a3b21ccf?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/8b72a3b21ccf</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 19:17:37 GMT</pubDate>
            <atom:updated>2025-01-10T09:22:31.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*I4cwWhCpfSQAZ0SxGP45pA@2x.jpeg" /><figcaption>Image created by the author with Ideogram.ai.</figcaption></figure><p><strong>The Mobile Stack</strong> exists to empower developers with insights and resources to build exceptional mobile experiences.</p><blockquote>Whether you’re sharing your expertise on tools, frameworks, coding techniques, or industry trends, your voice matters here.</blockquote><h3>How to submit your article</h3><p>Want to contribute? Follow these simple steps to be an <strong>Author</strong> <strong>for The Mobile Stack</strong>:</p><ol><li><strong>Follow us.</strong> Follow <a href="https://medium.com/u/96dd69cf281">Raúl Ferrer</a> and <strong>The Mobile Stack</strong>.</li><li><strong>Get added as an author. </strong>Drop a comment below telling why you would become an Author for The Mobile Stack.</li><li><strong>Follow these instructions to submit a story.</strong></li></ol><p><a href="https://help.medium.com/hc/en-us/articles/213904978-Add-draft-or-post-to-publication">Add a draft or post to publication</a></p><h3>Why publish with The Mobile Stack?</h3><ul><li><strong>Boost your reach.</strong> Articles published within a publication has more views on average.</li><li><strong>Own your content.</strong> Your stories remain yours. You’re free to cross-post or syndicate them as you like.</li><li><strong>Grow your brand.</strong> Share your blog, services, or portfolio tastefully in your articles to expand your influence.</li></ul><h3>What we look for</h3><p>We prioritize articles that are:</p><ul><li>Well-written and polished.</li><li>Not AI-written articles.</li><li>Aligned with Medium guidelines.</li><li>Relevant to mobile developers, designers, and tech enthusiasts.</li><li>Insightful, actionable, and engaging.</li></ul><h3>Topics our readers love</h3><p>Here’s a glimpse of what resonates with our community:</p><ul><li>Tutorials on mobile frameworks like <em>iOS</em>, <em>Android</em>, <em>Flutter</em>, <em>Swift</em>, <em>Kotlin</em>…</li><li>Step-by-step guides for building apps.</li><li>Comparative analyses of tools, libraries, or languages.</li><li>Trends in mobile development, like cross-platform vs. native debates.</li><li>Tips for optimizing performance or UI/UX.</li><li>Career advice for mobile developers.</li><li>Insights into launching apps or open-source projects.</li></ul><h3>Writing tips</h3><p>Focus on clarity, practical advice, and actionable insights. Your unique experience and perspective are what make your articles stand out.</p><p><strong>Always create original content and avoid copying or plagiarizing others’ work.</strong> <strong>Properly reference any images</strong> you use by citing the source to respect copyright and maintain credibility in your writing.</p><p>Ready to share your knowledge and grow with <strong>The Mobile Stack</strong>? Start writing today and join a community dedicated to shaping the future of mobile development.</p><p>Many articles have been written on how to craft a great story. One of the best resources is <a href="https://medium.com/u/8b318225c16a">freeCodeCamp</a>, and we highly recommend their editor’s handbook as a guide.</p><p><a href="https://www.freecodecamp.org/news/the-freecodecamp-medium-publication-editor-handbook-cb5876d1ef23">The freeCodeCamp Medium Publication Editor Handbook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b72a3b21ccf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/write-for-the-mobile-stack-share-your-expertise-in-mobile-development-8b72a3b21ccf">Write for The Mobile Stack: Share Your Expertise in Mobile Development</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add Dark Mode in iOS 13]]></title>
            <link>https://medium.com/the-mobile-stack/how-to-add-dark-mode-in-ios-13-8de17aee9e36?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/8de17aee9e36</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 15:28:39 GMT</pubDate>
            <atom:updated>2023-02-22T14:05:25.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QEz1FojKxuxKzr8y" /><figcaption>Photo by <a href="https://unsplash.com/@elliottengelmann?utm_source=medium&amp;utm_medium=referral">Elliott Engelmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Surely you have heard of Dark Mode on iOS 13, that is, a mode in which the color range of the user interface darkens. This allows, among other things, to improve visibility in places with low light and reduce the energy consumption of applications (dark colors use less energy than light ones).</p><p>Although some applications already included a Dark Mode in their interface, it was not until the publication of iOS 13 and iPadOS, that the Dark Mode was included in the configuration of the device itself. To change to Dark mode we have to go to <em>Settings&gt; Display</em> and brightness and select Dark mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGf3PbC7V4mzHoVHo1GSmQ.png" /></figure><h4>Adapt applications to Dark Mode</h4><p>To adapt an application to Dark Mode we must work with Xcode 11 and iOS 13. In addition, we must modify the colors and images used in the application.</p><p><strong>Use adaptive colors</strong></p><p>Colors that adapt automatically to the style of the interface should be used. For this we have two possibilities:<br>Use semantic colors. It is a set of colors prepared by Apple, which have two variants:<em> Dark Mode</em> and <em>Light Mode</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucaAo8VueBER2nG-ALuspQ.png" /></figure><p>To use these colors, for example, from the code, just write:</p><pre>let color = UIColor.systemGreen</pre><p>Or if we are in the Interface Builder, select it in the color attribute of the component we want to color.</p><h4>Define custom colors</h4><p>As we saw in <a href="https://www.raulferrergarcia.com/como-crear-una-paleta-de-colores-color-assets-en-xcode/">How to create a color palette (Color Assets) in Xcode</a>, we can define our own color palette in Xcode, so that we can call from any point of the application to these colors (both from the code and from the Interface Builder)</p><p>To do this, we select the Assets.xcassets folder (or creating our own .xcassets folder for colors) in the project navigator (Project Navigator).</p><p>Then we right-click, select New Color Set and change its attributes to generate the new color.</p><h4>Two versions of the same color</h4><p>But now we must generate two versions of the same color: the version of the light or default mode and that of the dark mode.</p><p>To do this, from the Color Attributes Inspector we have created, we select the Apperances attribute, and in the Any, Dark option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jbf-aQFe63Nrw6X-CGjDzA.png" /></figure><p>When doing this the color appears to us but with two versions: <em>Any Appearance</em> and <em>Dark Appearance</em>. From the property inspector we indicate the color for each of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbG1qm5ZhpX77WrXM3Z7VQ.png" /></figure><p>In this way, when the device mode is changed, our application will automatically take the color that corresponds to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbEMerDDSpJaOCPTJkv8pQ.png" /></figure><p>To be able to change the mode in the simulator, once the application is launched on it, we select the icon that represents two switches in the lower Xcode bar, and then indicate the interface style that we want to be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPvjbvj9Xd40uwVduerX-A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8de17aee9e36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/how-to-add-dark-mode-in-ios-13-8de17aee9e36">How to add Dark Mode in iOS 13</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 Tips for Avoiding Massive View Controllers in MVC-Based Swift Apps]]></title>
            <link>https://medium.com/the-mobile-stack/9-tips-for-avoiding-massive-view-controllers-in-mvc-based-swift-apps-9b3b1dd3f887?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/9b3b1dd3f887</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 15:27:42 GMT</pubDate>
            <atom:updated>2023-02-22T14:13:15.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_m7wp7bs3LQK-ukS" /><figcaption>Photo by <a href="https://unsplash.com/de/@kaip?utm_source=medium&amp;utm_medium=referral">Kai Pilger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <strong>Model-View-Controller</strong> (<strong>MVC</strong>) architecture pattern is a basic component of creating app user interfaces. However, when an app becomes more complicated, it’s not unusual for view controllers to get huge and cumbersome.</p><p>This can make the code difficult to comprehend and maintain and cause a number of issues, including lengthy build times and poor performance.</p><h3>Model-View-Controller components</h3><p>First of all, let’s remember which components make up the Model-View-Controller pattern and what their functions are.</p><h3>Model</h3><p>The <strong>Model </strong>holds de business logic and is in charge of accessing, manipulating, or storing the data of the application:</p><ul><li>Contains classes related to data persistence, like those which use databases (Core Data, SQLite, Realm…) or user preferences (UserDefaults).</li><li>Contains the classes that handles communications (Networking) and that allows the application to receive and send data.</li><li>Contains the classes that are in charge of parse the information received into the application (and convert it into model objects).</li><li>Contains extensions, constants, helper classes…</li><li>A model object can communicate with other model objects with 1:1 and 1:n relationships.</li><li>Direct communication between the Model and the View is not permitted. The Controller serves as the conduit for information exchange between the Model and the View.</li></ul><h3>View</h3><p>The <strong>View</strong> is composed by those components that the user can see:</p><ul><li>These classes are those that come from the UIKit, AppKit, Core Animation, and Core Graphics libraries.</li><li>Despite not being directly related to the Model, they display the data that originates from it (they do it through the Controller).</li><li>Users may interact with these elements.</li></ul><h3>Controller</h3><p>The <strong>Controller</strong> serves as a liaison between the <strong>Model</strong> and the <strong>View</strong>:</p><ul><li>It is the central element of the MVC model and interacts with both the Model and the View.</li><li>It receives and analyzes the user’s actions on the View, then updates the Model as necessary.</li><li>If the model’s data changes, the view is updated to reflect those changes.</li><li>It looks after the application’s life cycle.</li></ul><h3>Tips to avoid Massive-View-Controllers</h3><p>We’ll look at various tactics for avoiding large view controllers in MVC-based programs in this post. Your codebase will be easier to maintain and scale if you use these strategies to keep your view controllers compact, tidy, and understandable.</p><h3>1. Set distinct classes for view controller and logic</h3><p>The fact that view controllers frequently end up managing a broad range of duties unrelated to their primary function is one common cause of their size. A view controller, for instance, might be in charge of networking duties, data formatting, or business logic.</p><p>Consider separating the functionality that is not directly connected to the view controller’s primary duties into different classes to prevent this. You might develop a manager class to manage networking operations or a helper class to format data, for instance. By doing so, you’ll be able to divide up the functionality into smaller, simpler-to-manage chunks, which will also make the code easier to comprehend and maintain.</p><h3>2. Implement child view controllers</h3><p>Consider using child view controllers if your view controller contains several sections, each of which has a distinct set of duties. By doing so, you’ll be able to divide up the functionality into smaller, simpler-to-manage chunks, which will also make the code easier to comprehend and maintain.</p><p>You must first establish a container view in your main view controller before adding the child view controllers as children of the main view controller in order to use child view controllers. The content of the child view controllers can then be shown using the container view.</p><h3>3. Employ delegation</h3><p>Consider transferring the delegate methods to a different class if your view controller manages a lot of delegate methods. By doing so, you can make your view controller smaller and simpler to understand.</p><p>Define a protocol with the delegate methods you want to utilize before having your view controller adopt it in order to use delegation. Then, you may make a different class to serve as the delegate and provide a particular instance of it to your view controller as required.</p><h3>4. Utilize notifications</h3><p>Consider transferring the notification handling logic to a different class if your view controller is handling a lot of alerts. By doing so, you can make your view controller smaller and simpler to understand.</p><p>Create a notification observer in your view controller before registering for the alerts you want to receive in order to use notifications. When necessary, you can send a class instance to your view controller and construct a separate class to handle the notification events.</p><h3>5. Use model classes</h3><p>Consider developing model classes to manage the data if your view controller is in charge of processing a lot of data. Making your code more understandable will be made possible by separating the view controller from the data management logic.</p><p>Model classes should be made to be independent of the view controller and should provide the attributes and methods required to manage the data. This will increase the modularity and maintainability of your codebase and make it simpler to reuse the model classes in other areas of your application.</p><h3>6. Implement protocols and protocol extensions</h3><p>In Swift, protocols are a useful tool for outlining a class’s anticipated behavior. You can describe a collection of methods and attributes that a class must implement using protocols without mentioning the specific implementation. You can write more modular, reusable code as a result.</p><p>A protocol’s methods can have default implementations by using protocol extensions. If you have several view controllers that must implement the same set of methods, this can be extremely helpful. You can avoid repeatedly writing the same code in each view controller by using protocol extensions.</p><h3>7. Employ custom view classes</h3><p>Consider putting a lot of the view-related code in your view controller onto a separate custom view class. By doing so, you can make your view controller smaller and simpler to understand.</p><p>It is simpler to reuse and maintain view-related code when it is encapsulated in a single location using custom view classes. To further style and modify the user interface of your app, you can add new interface elements like buttons or text fields using custom view classes.</p><h3>8. Use dependency injection</h3><p>By using the dependency injection technique, objects (such services or helpers) can be passed into a class as dependencies rather than being created there. This can make your view controller smaller and simpler, which will make testing easier.</p><p>Define a protocol for the dependency you wish to inject, and then send an instance of that dependency to your view controller when it is initialized if you want to use dependency injection. This will make it simple for you to switch between several dependency implementations as necessary and will facilitate isolation testing for your view controller.</p><h3>9. Utilize functional programming methods</h3><p><em>Map</em>, <em>filter</em>, and <em>reduce</em> are examples of functional programming techniques that can be used to build more terse and expressive code. These methods enable declarative manipulation of data sets, which can facilitate code comprehension and maintenance.</p><p>If you want to make your view controller logic simpler and clearer, think about adopting functional programming techniques. For instance, you could use filter to choose a subset of data based on specific criteria or map to change the format of an array of data.</p><h3>Conclusion</h3><p>The MVC architecture pattern in Swift allows you to avoid huge view controllers using a variety of techniques. Your codebase will be easier to maintain and scale by keeping your view controllers compact, well-organized, and understandable if you adhere to best practices like isolating logic into distinct classes, employing child view controllers, and using functional programming approaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b3b1dd3f887" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/9-tips-for-avoiding-massive-view-controllers-in-mvc-based-swift-apps-9b3b1dd3f887">9 Tips for Avoiding Massive View Controllers in MVC-Based Swift Apps</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design patterns in software]]></title>
            <link>https://medium.com/the-mobile-stack/design-patterns-in-software-b5fc4baa9595?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/b5fc4baa9595</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 15:27:21 GMT</pubDate>
            <atom:updated>2023-02-22T14:14:17.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*su9RH-expmaRRAQ3" /><figcaption>Photo by <a href="https://unsplash.com/@sxoxm?utm_source=medium&amp;utm_medium=referral">Sven Mieke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Normally, in software development we often encounter problems that have similar characteristics. To solve them we find different solutions, but as some of these solutions are usually better than others (from the point of view of flexibility and reusability), they end up being preferred. These solutions end up becoming Design Patterns in software. Design Patterns in software are solutions to recurring design problems that are being applied daily in the software industry.</p><p>Design patterns allow developers to have a guide when establishing the <a href="https://medium.com/@raulferrer/pros-and-cons-of-some-ios-architecture-patterns-efeb324ee29">structure of a program, and make it more flexible and reusable</a>. In addition, it also allows solving problems with a methodology already tested and not doing so from scratch.</p><h3>How many design patterns in software are there?</h3><p>There are <strong>23 design patterns</strong>, which were described in the book <a href="https://www.oreilly.com/library/view/design-patterns-elements/0201633612/">Design Patterns, Elements of Reusable Object-Oriented Software</a> by E. Gamma , R. Helm, E. Johnson and J. Vlissides. This group of authors are considered the ‘Gang of Four’ and as the gurus of the design patterns in software. These authors described the 23 design patterns and classified them into three groups: structural patterns, creational patterns and behaviour patterns.</p><h4>Creational Patterns</h4><p>Creational patterns are those that allow us to create objects. These patterns encapsulate the procedure for creating an object and usually work through interfaces:</p><ul><li><strong>Factory Method.</strong> It provides an interface that allows you to create objects in a superclass, but delegates its implementation and alteration of the objects in the subclasses.</li><li><strong>Abstract Factory.</strong> It provides an interface that allows generating groups of related objects, but without specifying their specific classes or their implementation.</li><li><strong>Builder.</strong> It allows to build complex objects step by step, separating the object creation from its structure. In this way we can use the same construction process to obtain different types and representations of an object.</li><li><strong>Singleton.</strong> This pattern ensures that a class has only one possible instance, which can be accessed globally.</li><li><strong>Prototype. </strong>It allows you to copy or clone an object without the need for our code to depend on its classes.</li></ul><h3>Structural patterns</h3><p>Structural patterns specify how objects and classes relate to each other to form more complex structures, so that they are flexible and efficient. They rely on inheritance to define interfaces and obtain new functionalities:</p><ul><li><strong>Adapter. </strong>It is a structural pattern that allows two objects with incompatible interfaces to collaborate, through an intermediary with which they communicate and interact.</li><li><strong>Bridge.</strong> In this pattern, an abstraction is decoupled of its implementation is decoupled, so that they can evolve independently.</li><li><strong>Composite.</strong> It allows you to create objects with a tree-like structure, and then work with these structures as if they were individual objects. In this case all the elements of the structure use the same interface.</li><li><strong>Decorator.</strong> This pattern allows new functionalities to be added to an object (including this object in a wrapper that contains the new functionalities) without modifying the behaviour of objects of the same type.</li><li><strong>Facade.</strong> It provides a simplified interza to a complex structure (such as a library or a set of classes).</li><li><strong>Flyweight.</strong> It is a pattern that allows you to save RAM, since it causes many objects to share common properties in the same object, instead of maintaining these properties in each and every object.</li><li><strong>Proxy.</strong> It is an object that acts as a simplified version of the original. A proxy controls access to the original object, which allows us to perform some tasks before or after accessing that object. This pattern is usually used in internet connections, access to device files, etc. That is to say expensive processes, and allows to reduce the cost and complexity.</li></ul><h3>Behavioural patterns</h3><p>They are the most numerous, focus on communication between objects and are responsible for managing algorithms, relationships and responsibilities between these objects:</p><ul><li><strong>Chain of Responsibility.</strong> It allows to pass requests through a chain of handlers. Each of these handlers can process the request or pass it on to the next one. In this way the sender and the final receiver are decoupled.</li><li><strong>Command.</strong> Transform a request into an object that encapsulates the action and the information you need to execute it.</li><li><strong>Interpreter.</strong> It is a pattern that, given a language, defines a representation for its grammar and the mechanism to evaluate it.</li><li><strong>Iterator.</strong> It allows to circulate through the elements of a collection without exposing its representation (list, stack, tree…).</li><li><strong>Mediator.</strong> It restricts direct communications between objects and forces communication through a single object, which acts as a mediator.</li><li><strong>Memento.</strong> It allows saving and restoring an object to a previous state without revealing the details of its implementation.</li><li><strong>Observe. </strong>It allows establishing a subscription mechanism to notify different objects of the events that occur in the object they observe.</li><li><strong>State.</strong> It allows an object to change its behavior when its internal state changes. It seems that his class had changed.</li><li><strong>Strategy.</strong> It allows to define that, from a family of algorithms, we can select one of them at runtime to perform a certain action.</li><li><strong>Template Method</strong>. This pattern defines the skeleton of an algorithm in a superclass, but allows subclasses to redefine some methods without changing their structure.</li><li><strong>Visitor.</strong> It allows to separate the algorithms from the objects with which they operate.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5fc4baa9595" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/design-patterns-in-software-b5fc4baa9595">Design patterns in software</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VIP Architecture with Coordinator]]></title>
            <link>https://medium.com/the-mobile-stack/vip-architecture-with-coordinator-17aee5ddacd4?source=rss----e72cc1d2e5fd---4</link>
            <guid isPermaLink="false">https://medium.com/p/17aee5ddacd4</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[vip]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Raúl Ferrer]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 15:26:53 GMT</pubDate>
            <atom:updated>2023-02-22T14:18:14.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vsfRtOD4w5IONaSV" /><figcaption>Photo by <a href="https://unsplash.com/@mbenna?utm_source=medium&amp;utm_medium=referral">Mike Benna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Clean Swift</strong>, also known as<strong> VIP (View-Interactor-Presenter) architecture</strong>, is an iOS application design pattern that <a href="https://clean-swift.com/">Raymond Law introduced it in 2014</a> as an alternative to the popular Model-View-Controller (MVC) pattern. VIP architecture’s primary goal is to make the codebase more modular, testable, and scalable.</p><h3>When should you use VIP architecture?</h3><p>VIP architecture is well suited for large, complex iOS applications that necessitate the collaboration of multiple developers. It’s also useful for applications that need a lot of test coverage and upkeep.</p><h3>VIP Components</h3><p>VIP architecture is made up of five major components:</p><h4>View</h4><p>The <strong>View</strong> layer is in charge of displaying data to the user as well as handling user interactions. It is a passive layer that is unaware of the underlying business logic.</p><h4>Interactor</h4><p>The <strong>Interactor</strong> layer contains the application’s business logic. It receives requests from the Presenter layer and executes the required operations. Data retrieval, processing, and validation are all handled by the Interactor layer.</p><h4>Presenter</h4><p>The <strong>Presenter</strong> layer acts as a go-between for the View and the Interactor. It takes user input from the View and sends it to the Interactor for processing. The Presenter layer is also in charge of formatting data from the Interactor and passing it to the View for display.</p><h4>Router</h4><p>The <strong>Router</strong> layer is in charge of application navigation. Based on user actions and business logic, it determines which screen to display.</p><h4>Entities</h4><p><strong>Entities</strong> represent the application’s data models. They include the properties and methods necessary to represent business objects. Swift structs or classes are commonly used to implement Entities.</p><h3>Using a Configurator</h3><p>The <strong>Configurator</strong> component in the VIP architecture pattern is in charge of configuring components for a given view controller. The Configurator is typically implemented as a separate class or module, with the goal of decoupling the VIP component setup from the view controller itself.</p><p>The Configurator creates and configures the view controller’s VIP components, such as the Interactor, Presenter, and Router. It also creates the links between the components and the view controller and returns the view controller with the components attached once the components have been configured.</p><p>The Configurator allows to encapsulate and segregate the components from the view controller. Additionally, because the VIP components can be tested independently of the view controller, it offers a cleaner, more modular codebase that is simpler to test.</p><h3>Example code</h3><p>Let’s see an schematic example of the application of VIP architecture with Configurator. As one of the main drawbacks of the VIP architecture is the boilerplate code need for fill all the classes in a scene, we will <a href="https://raulferrer.dev/blog/xcode_templates/">use a template</a> (you can find many Xcode templates for VIP over Internet).</p><h4>View+ViewController</h4><pre>protocol ExampleViewDelegate: class {}<br><br>final class ExampleView: UIView {<br>    <br>    weak var delegate: ExampleViewDelegate?<br><br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        configureUI()<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    func configureUI() {}<br>}</pre><pre>import UIKit<br><br>protocol ExampleViewControllerInput: class {}<br><br>protocol ExampleViewControllerOutput: class {}<br><br>final class ExampleViewController: UIViewController {<br>    var interactor: ExampleInteractorInput?<br>    var router: ExampleRouterDelegate?<br>    <br>    private let sceneView: ExampleView<br>    <br>    init(sceneView: ExampleView) {<br>        self.sceneView = sceneView<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        sceneView.delegate = self<br>        self.view = sceneView<br>    }<br>}<br><br>extension ExampleViewController: ExampleViewControllerInput {}<br><br>extension ExampleViewController: ExampleViewDelegate {}</pre><h4>Interactor</h4><pre>import Foundation<br><br>protocol ExampleInteractorOutput: class { }<br><br>typealias ExampleInteractorInput = ExampleViewControllerOutput<br><br>final class ExampleInteractor {<br>    var presenter: ExamplePresenterInput?<br>}<br><br>extension ExampleInteractor: ExampleInteractorInput {}</pre><h4>Presenter</h4><pre>import UIKit<br><br>typealias ExamplePresenterInput = ExampleInteractorOutput<br>typealias ExamplePresenterOutput = ExampleViewControllerInput<br><br>final class ExamplePresenter {<br>    weak var viewController: ExamplePresenterOutput?<br>}<br><br>extension ExamplePresenter: ExamplePresenterInput {}</pre><h4>Router</h4><pre>import UIKit<br><br>protocol ExampleRouterDelegate {}<br><br>final class ExampleRouter {<br>    weak var viewController: UIViewController?<br>}<br><br>extension ExampleRouter: ExampleRouterDelegate {}</pre><h4>Configurator</h4><pre>import Foundation<br><br>final class ExampleConfigurator {<br>    <br>    static func configure( _ viewController: ExampleViewController) -&gt; ExampleViewController {<br>        <br>        let interactor = ExampleInteractor()<br>        let presenter = ExamplePresenter()<br>        let router = ExampleRouter()<br>        router.viewController = viewController<br>        presenter.viewController = viewController<br>        interactor.presenter = presenter<br>        viewController.interactor = interactor<br>        viewController.router = router<br>        return viewController<br>    }<br>}</pre><h3>Configuraton code explained</h3><p>In the ExampleConfigurator, we have a method (configure) that takes an instance of ExampleViewController as an argument and returns an instance of ExampleViewController, which will be ‘configured’. Inside this method, this is waht occurs:</p><ul><li>Instances of ExampleInteractor, ExamplePresenter, and ExampleRouter are created.</li><li>The viewController properties of the router and the presenter are set to the viewController passed.</li><li>The presenter property of the interactor instance is set to the presenter instance created at the beginning.</li><li>The interactor and router instances are assigned to the interactor and router properties of the viewController.</li><li>Finnally, the ‘configured’ viewController passed to the function is returned. So we have set up all the dependencies required for the ExampleViewController scene to work.</li></ul><h3>Protocols nomenclature</h3><p>As you have seen, there are a lot of protocols that allows the flow of informaction. In this case, we have also use a <em>Input/Output</em> convention to define the inputs and outputs of each component. In order to accomplish that, we use <em>typealias</em> to ‘rename’ this protocols in each case.</p><h3>Advantajes and drawbacks</h3><p>As any other architecture, VIP has advantajes and drawbacks.</p><h4>Advantajes</h4><ul><li>Follows Clean Architecture’s principles.</li><li>The flow of data is unidirectional.</li><li>Uses Simple Responsibility Principle, which results in smaller methods.</li><li>Uses protocols (interfaces) in order to make code more modular and reusable (so we can change one piece for another without impact on the rest of the application).</li><li>It’s easy to maintain and debug.</li><li>Unit tests can be easily added.</li></ul><h4>Drawbacks</h4><ul><li>VIP have a lot of protocols and boilerplate code, which can be confusing. It’s advisable to use templates.</li><li>For newbies could be overhelming, as at first sight seems over-engineered.</li><li>Is not usually recommended in small applications.</li><li>It must be taken into account that, although it is a small functionality to add, the amount of code to write is high.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17aee5ddacd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-mobile-stack/vip-architecture-with-coordinator-17aee5ddacd4">VIP Architecture with Coordinator</a> was originally published in <a href="https://medium.com/the-mobile-stack">The Mobile Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>