<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Marwan Ayman</title>
    <description>The latest articles on DEV Community by Marwan Ayman (@marwan8).</description>
    <link>https://dev.to/marwan8</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F430782%2F01ad385c-e09d-423e-b35b-157aaf905154.JPG</url>
      <title>DEV Community: Marwan Ayman</title>
      <link>https://dev.to/marwan8</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/marwan8"/>
    <language>en</language>
    <item>
      <title>Swift tips and tricks for beginners</title>
      <dc:creator>Marwan Ayman</dc:creator>
      <pubDate>Tue, 28 Feb 2023 19:16:31 +0000</pubDate>
      <link>https://dev.to/marwan8/swift-tips-and-tricks-for-beginners-3aop</link>
      <guid>https://dev.to/marwan8/swift-tips-and-tricks-for-beginners-3aop</guid>
      <description>&lt;p&gt;Swift is a powerful and modern programming language used to build applications for Apple’s platforms. In this article, we’ll explore some tips and tricks for programming in Swift that can help you write better code and improve your productivity.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Use guard statements
&lt;/h2&gt;

&lt;p&gt;Guard statements are a great way to improve the readability and maintainability of your code. They allow you to exit early from a function if certain conditions are not met, which can help you avoid nested if statements and improve the flow of your code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;guard let param1 = param1, let param2 = param2 else {
  print("Missing parameters")
  return
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Use optional binding wisely.
&lt;/h2&gt;

&lt;p&gt;Optionals are a core feature of Swift that allow you to represent values that may or may not be present. While optionals can be powerful, they can also be a source of confusion and bugs if not used properly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if let optionalValue = optionalValue {
  // Code that uses optionalValue
}

let length = optionalValue?.count ?? 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Use Extensions to Organize Your Code.
&lt;/h2&gt;

&lt;p&gt;Use extensions to add functionality to existing types without subclassing them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension String {
  func capitalizeFirstLetter() -&amp;gt; String {
    return prefix(1).uppercased() + dropFirst()
  }
}

let myString = "hello world"
print(myString.capitalizeFirstLetter()) // Output: "Hello world"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Use Enums to Represent Finite States
&lt;/h2&gt;

&lt;p&gt;Enums are a great way to represent finite states in your code. They can make your code more expressive and less error-prone by ensuring that only valid states are used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum NetworkState {
  case loading
  case loaded(data: Data)
  case error(error: Error)
}

func handleNetworkState(_ state: NetworkState) {
  switch state {
  case .loading:
    print("Loading...")
  case .loaded(let data):
    print("Data loaded: \(data)")
  case .error(let error):
    print("Error occurred: \(error)")
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Use closures to simplify your code and make it more readable.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [1, 2, 3, 4, 5]
let doubledNumbers = numbers.map { $0 * 2 }
print(doubledNumbers) // Output: [2, 4, 6, 8, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are just a few tips and tricks to help you write better Swift code. With practice and experience, you’ll discover many more ways to improve your coding skills and create amazing apps.&lt;/p&gt;

&lt;p&gt;Reach me out &lt;a href="https://marwanayman.com/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>security</category>
      <category>selfhost</category>
      <category>networking</category>
    </item>
    <item>
      <title>SOLID Principles in Swift: A Practical Guide</title>
      <dc:creator>Marwan Ayman</dc:creator>
      <pubDate>Sun, 29 Jan 2023 20:40:09 +0000</pubDate>
      <link>https://dev.to/marwan8/solid-principles-in-swift-a-practical-guide-1fgk</link>
      <guid>https://dev.to/marwan8/solid-principles-in-swift-a-practical-guide-1fgk</guid>
      <description>&lt;p&gt;The SOLID principles are a set of guidelines for writing maintainable and scalable software. They were first introduced by Robert C. Martin in his book “Agile Software Development, Principles, Patterns, and Practices”. These principles are widely used in object-oriented programming languages, such as Swift.&lt;/p&gt;

&lt;h2&gt;
  
  
  Single Responsibility Principle (SRP)
&lt;/h2&gt;

&lt;p&gt;The single responsibility principle states that a class should have one, and only one, reason to change. This means that a class should have a single, well-defined responsibility. In other words, a class should have only one reason to exist and all its methods should be related to that reason.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User {
    var name: String
    var email: String
    init(name: String, email: String) {
        self.name = name
        self.email = email
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the User class has only one responsibility: to store and retrieve information about a user. It has no other responsibilities, such as sending an email or validating the user’s information. This makes it easy to understand and maintain.&lt;/p&gt;

&lt;h2&gt;
  
  
  Open-Closed Principle (OCP)
&lt;/h2&gt;

&lt;p&gt;The open-closed principle states that a class should be open for extension, but closed for modification. This means that a class should be designed in such a way that new functionality can be added without modifying the existing code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol Shape {
    func area() -&amp;gt; Double
}

class Rectangle: Shape {
    var width: Double
    var height: Double

    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }

    func area() -&amp;gt; Double {
        return width * height
    }
}

class Circle: Shape {
    var radius: Double

    init(radius: Double) {
        self.radius = radius
    }

    func area() -&amp;gt; Double {
        return Double.pi * radius * radius
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have a protocol “Shape” which has a function area(). The class “Rectangle” and “Circle” conforms to the Shape protocol and implements the area() function. Now, if we need to add a new shape, for example, a triangle, we can just create a new class “Triangle” which conforms to the Shape protocol and implements the area() function. We don’t need to modify the existing class, which makes it easy to add new functionality and maintain the code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Liskov Substitution Principle (LSP)
&lt;/h2&gt;

&lt;p&gt;The Liskov substitution principle states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program. This means that a subclass should be a subtype of its superclass, and should be able to replace any instance of its superclass without affecting the correctness of the program.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car {
  func startEngine() {
    print("Engine started")
  }
}

class ElectricCar: Car {
  override func startEngine() {
    print("Electric motor started")
  }
}

let car: Car = ElectricCar()
car.startEngine()  // Output: "Electric motor started"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we have a Car class and a ElectricCar subclass that inherit from it. Since ElectricCar overrides the startEngine() method and the ElectricCar instance can be assigned to a variable of type Car, LSP is satisfied.&lt;/p&gt;

&lt;h2&gt;
  
  
  Interface Segregation Principle (ISP)
&lt;/h2&gt;

&lt;p&gt;The Interface Segregation Principle states that a class should not be forced to implement interfaces it doesn’t use. In other words, a class should only be required to implement the methods it needs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol Printable {
  func printDocument()
  func scanDocument()
  func faxDocument()
}

class Printer: Printable {
  func printDocument() {
    // Code to print document
  }

  func scanDocument() {
    // Not implemented
  }

  func faxDocument() {
    // Not implemented
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we have a Printable protocol with three methods. The Printer class only needs to implement the printDocument() method, but it is forced to implement the other two methods as well. To adhere to ISP, we can split the Printable protocol into two separate protocols: Printable and Scanable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol Printable {
  func printDocument()
}

protocol Scanable {
  func scanDocument()
}

class Printer: Printable {
  func printDocument() {
    // Code to print document
  }
}

class Scanner: Scanable {
  func scanDocument() {
    // Code to scan document
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Dependency Inversion Principle (DIP)
&lt;/h2&gt;

&lt;p&gt;The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but both should depend on abstractions. In other words, a class should not depend on a specific implementation, but rather on an abstraction.&lt;/p&gt;

&lt;p&gt;Let’s take a look at an example where DIP is not followed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Database {
  func save(data: String) {
    // Code to save data to database
  }
}

class User {
  var database = Database()

  func save() {
    database.save(data: "user data")
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the User class depends directly on the Database class. If we need to change the implementation of the database, we would have to change the User class as well. This creates a tight coupling between the two classes and makes the code less flexible and harder to maintain.&lt;/p&gt;

&lt;p&gt;To adhere to DIP, we can create an abstraction in the form of a protocol and have both the User and Database classes depend on it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol DataStorage {
  func save(data: String)
}

class Database: DataStorage {
  func save(data: String) {
    // Code to save data to database
  }
}

class User {
  var dataStorage: DataStorage

  init(dataStorage: DataStorage) {
    self.dataStorage = dataStorage
  }

  func save() {
    dataStorage.save(data: "user data")
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the User class depends on the DataStorage protocol, rather than a specific implementation. This allows us to change the implementation of the database without affecting the User class.&lt;/p&gt;

&lt;p&gt;DIP allows us to create more flexible and maintainable code by decoupling classes and making them depend on abstractions rather than specific implementations. It is an important principle to keep in mind when designing and implementing software.&lt;/p&gt;

&lt;p&gt;Another way to follow DIP is to use Dependency injection. Dependency injection is a design pattern that allows us to provide an object with its dependencies, rather than creating them directly within the class. This allows us to change the implementation of the dependencies without affecting the class using them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Database: DataStorage {
  func save(data: String) {
    // Code to save data to database
  }
}

class User {
  var dataStorage: DataStorage

  init(dataStorage: DataStorage = Database()) {
    self.dataStorage = dataStorage
  }

  func save() {
    dataStorage.save(data: "user data")
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way we can use a different implementation of the DataStorage protocol and use it in the User class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CloudStorage: DataStorage {
  func save(data: String) {
    // Code to save data to cloud
  }
}

let user = User(dataStorage: CloudStorage())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In conclusion, the SOLID principles are a set of guidelines that help us create more maintainable and flexible code. These principles, Single Responsibility Principle, Open-Closed Principle, Liskov Substitution Principle, Interface Segregation Principle and Dependency Inversion Principle, are essential to consider when designing and implementing software.&lt;/p&gt;

&lt;p&gt;By following these principles, we can create classes that are easy to understand, test, and change. They also help us avoid common design problems such as tight coupling and fragile code.&lt;/p&gt;

&lt;p&gt;In this article, we have seen examples of how to implement SOLID principles in swift. By following these principles, we can create code that is more maintainable, flexible and easy to understand. These principles should be considered as a guide to help make our code more robust and scalable.&lt;/p&gt;

&lt;p&gt;In short, SOLID principles are a set of guidelines that help us create more maintainable and flexible code. By following these principles, we can create code that is more robust and scalable, which is essential for building high-quality software.&lt;/p&gt;

&lt;p&gt;Reach me out &lt;a href="https://marwanayman.com/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>express</category>
      <category>postman</category>
      <category>tooling</category>
      <category>showdev</category>
    </item>
    <item>
      <title>iOS unit test mocking using SwiftyMocky</title>
      <dc:creator>Marwan Ayman</dc:creator>
      <pubDate>Sun, 27 Nov 2022 16:37:24 +0000</pubDate>
      <link>https://dev.to/marwan8/ios-unit-test-mocking-using-swiftymocky-2h8c</link>
      <guid>https://dev.to/marwan8/ios-unit-test-mocking-using-swiftymocky-2h8c</guid>
      <description>&lt;p&gt;Swift was designed to be safe — supporting read-only reflection. Thus, there’s no way to modify your program at runtime. Overall, it’s good, the code is executed as expected, and other components cannot change it. But leading back to our topic, all mocking frameworks are built on reflection to be able to change classes, types, and objects on runtime.&lt;/p&gt;

&lt;p&gt;This language needs its superheroes to write testable code, and we know them well — protocols and extensions! No matter what implementation it is — class, enum, or struct — the purpose of protocols remains — to define abstractions and add new functionality to types, even ones we don’t owe.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What we can do to mock?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use meta-programming to generate complete mock implementation.&lt;/p&gt;

&lt;p&gt;They are many libraries doing the mock job for the unit testing, most poplar are Cuckoo and swifyMocky.&lt;/p&gt;

&lt;p&gt;In this article, I will give overview on how we can do the mocking using SwiftyMocky.&lt;/p&gt;

&lt;h2&gt;
  
  
  SwiftyMocky
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://github.com/MakeAWishFoundation/SwiftyMocky" rel="noopener noreferrer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Automatically mock Swift protocols&lt;/li&gt;
&lt;li&gt;Support generics&lt;/li&gt;
&lt;li&gt;Straightforward setup and lightweight&lt;/li&gt;
&lt;li&gt;Good documentation&lt;/li&gt;
&lt;li&gt;Nice and easy syntax (that utilizes auto-complete)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Mock generation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mark protocols to be mocked&lt;/li&gt;
&lt;li&gt;Every protocol in source directories, having this annotation, will be added to Mock.generated.swift&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnd4dau49ik0luuw7zuzr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnd4dau49ik0luuw7zuzr.png" alt="Image description" width="737" height="142"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stubbing&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All mocks has given method (accessible both as instance method or global function), with easy to use syntax, allowing to specify what should be return values for given methods (based on specified attributes)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdh0ycwghce93g05l46rx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdh0ycwghce93g05l46rx.png" alt="Image description" width="687" height="252"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Spying&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;All mocks has verify method (accessible both as instance method or global function), with easy to use syntax, allowing to verify, whether a method was called on mock, and how many times. It also provides convenient way to specify, whether method attributes matters (and which ones)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;All mocks has perform method (accessible both as instance method or global function), with easy to use syntax, allowing to specify closure, that will be executed upon stubbed method being called&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F07lybg1gkde44vwwlaod.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F07lybg1gkde44vwwlaod.png" alt="Image description" width="687" height="252"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5gxvxxum7f0lwetrelq5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5gxvxxum7f0lwetrelq5.png" alt="Image description" width="800" height="90"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Autocomplete&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faeia7kuuejeiyqo05jye.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faeia7kuuejeiyqo05jye.gif" alt="Image description" width="480" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setup&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Install using Cocoapods&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Instal CLI for easy mock generation&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;swiftymocky setup # if you don’t have a Mockfile yet&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;swiftymocky doctor # validate your setup&lt;/p&gt;

&lt;p&gt;swiftymocky generate # generate mocks&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Mocks generation is based on Mockfile.yml file with possibility to exclude swift lint rules using excludedSwiftLintRules&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Not so many tools we, as developers, have for mocking on Swift, with some strict boundaries due to language limited runtime access. And here we come to the critical question — use or not to use external frameworks for mocking.&lt;/p&gt;

&lt;p&gt;Well-known Uncle Bob keeps not using them as much as possible; he says: “&lt;em&gt;The point at which you start to need a mocking framework is the very point at which the coupling between your tests and code is getting too high. After that, however, You should strive to keep the coupling between your code and tests low enough that you don’t need to use the mocking framework very often.&lt;/em&gt;”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thank you for reading! If you liked this article, please clap so other people can read it too :)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Happy coding ✌️&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Reach me out &lt;a href="https://marwanayman.com/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>docker</category>
      <category>devops</category>
      <category>programming</category>
    </item>
    <item>
      <title>Getting Started with the VIPER Architecture Pattern for iOS Application Development</title>
      <dc:creator>Marwan Ayman</dc:creator>
      <pubDate>Sun, 20 Nov 2022 13:43:49 +0000</pubDate>
      <link>https://dev.to/marwan8/getting-started-with-the-viper-architecture-pattern-for-ios-application-development-2oee</link>
      <guid>https://dev.to/marwan8/getting-started-with-the-viper-architecture-pattern-for-ios-application-development-2oee</guid>
      <description>&lt;p&gt;When you are planning to build an app, one of the most important decisions is to choose how to structure your app’s core.&lt;/p&gt;

&lt;p&gt;Better saying, you need to decide which architecture you should adopt to build all your screens, features, and contexts. You need to know how to organize your app in order to make it maintainable for the long term, testable, scalable, and understandable by anyone who enters the project sometime later. In this article, we will get familiar with a design pattern called VIPER (View, Interactor, Presenter, Entity, and Router.) for iOS development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is VIPER?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;VIPER is an architectural pattern like MVC or MVVM, but it separates the code further by single responsibility.&lt;br&gt;
One feature, one module. For each module, VIPER has five different classes with distinct roles. No class goes beyond its sole purpose.&lt;/p&gt;

&lt;p&gt;Each of the letters in VIPER stand for a component of the architecture: View, Interactor, Presenter, Entity and Router.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;View&lt;/strong&gt; is the user interface. This layer is the ViewController together with the UIView(or xib/storyboard)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Interactor&lt;/strong&gt; contains business logic related to the data (Entities) or networking, like creating new instances of entities or fetching them from the server. For those purposes you’ll use some Services and Managers which are not considered as a part of VIPER module but rather an external dependency&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Presenter&lt;/strong&gt; is directing data between the view and interactor, taking user actions and calling to router to move the user between views.The only class to communicate with all the other components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Entity&lt;/strong&gt; is your plain data objects, not the data access layer, because that is a responsibility of the Interactor.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Router&lt;/strong&gt; handles navigation between the VIPER modules.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl5103nmzqxl6u98z5fca.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl5103nmzqxl6u98z5fca.png" alt="Image VIPER"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Below I will explain an example of VIPER&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Protocols&lt;/strong&gt;&lt;br&gt;
I have created a separate file for all the protocols&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

protocol NewsListView: AnyObject {
}

protocol NewsListPresenter: AnyObject {
    func viewDidLoad(view: NewsListView)
}

protocol NewsListInteractorInput: AnyObject {
}

protocol NewsListInteractorOutput: AnyObject {
}

protocol NewsListRouter: AnyObject {
}

protocol NewsListRepo: AnyObject {

}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see from the above code, this is the main contract agreement between VIPER layers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Presenter&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;PresenterImplementation is an implementation of NewsListPresenter protocol and confirm the NewsListInteractorOutput.&lt;/p&gt;

&lt;p&gt;In this layer presenter has a reference object from &lt;strong&gt;View&lt;/strong&gt;, &lt;strong&gt;Router&lt;/strong&gt; and &lt;strong&gt;Interactor&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListPresenterImplementation: NewsListPresenter{

    private weak var view: NewsListView?
    private let router: NewsListRouter
    private let interactor: NewsListInteractorInput

    init(router: NewsListRouter, interactor: NewsListInteractorInput) {
        self.router = router
        self.interactor = interactor
    }

    func viewDidLoad(view: NewsListView) {
        self.view = view
    }
}

extension NewsListPresenterImplementation: NewsListInteractorOutput {

}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Interactor&lt;/strong&gt;&lt;br&gt;
Interactor is an implementation of NewsListInteractorInput protocol&lt;/p&gt;

&lt;p&gt;NewsListRepo is responsible to fetch the data from network or Data provider&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListInteractor: NewsListInteractorInput {

    weak var output: NewsListInteractorOutput?

    private let repo: NewsListRepo

    init(repo: NewsListRepo) {
        self.repo = repo
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;View&lt;/strong&gt;&lt;br&gt;
View is a UIViewController with a confirmation of NewsListView protocol and it has reference to the presenter&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListViewController: UIViewController, NewsListView {

    private let presenter: NewsListPresenter

    init(presenter: NewsListPresenter) {
        self.presenter = presenter

        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        presenter.viewDidLoad(view: self)
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Entity&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

struct News {
    let title: String
    let url: URL
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Router&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListRouterImplementation: NewsListRouter {

    weak var viewController: UIViewController?

}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we need to update our VIPER module to fetch the news data, yes as you are thinking right now, we need to update our contract protocols first&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

protocol NewsListView: AnyObject {
    func show(newsList: [News])
}

protocol NewsListPresenter: AnyObject {
    func viewDidLoad(view: NewsListView)
}

protocol NewsListInteractorInput: AnyObject {
    func fetchNewsList()
}

protocol NewsListInteractorOutput: AnyObject {
    func fetchNewsListSuccess(newsList: [News])
    func fetchNewsListFailure(error: Error?)
}

protocol NewsListRepo: AnyObject {
    func fetchNewsList(completion: @escaping ([News]?, Error?) -&amp;gt; Void)
}

protocol NewsListRouter: AnyObject {
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let’s now add implementation for theses added funcs in the protocols&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interactor&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListRepoImplementationl: NewsListRepo {
    func fetchNewsList(completion: @escaping ([News]?, Error?) -&amp;gt; Void) {
        // Fetch the data with completion
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListInteractor: NewsListInteractorInput {

    weak var output: NewsListInteractorOutput?

    private let repo: NewsListRepo

    init(repo: NewsListRepo) {
        self.repo = repo
    }

    func fetchNewsList() {
        repo.fetchNewsList { news, error in
            if let newsList = news {
                self.output?.fetchNewsListSuccess(newsList: newsList)
            } else {
                self.output?.fetchNewsListFailure(error: error)
            }
        }
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Presenter&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListPresenterImplementation: NewsListPresenter{

    private weak var view: NewsListView?
    private let router: NewsListRouter
    private let interactor: NewsListInteractorInput

    init(router: NewsListRouter, interactor: NewsListInteractorInput) {
        self.router = router
        self.interactor = interactor
    }

    func viewDidLoad(view: NewsListView) {
        self.view = view
        // Fetch the list from the interactor
        interactor.fetchNewsList()
    }
}

extension NewsListPresenterImplementation: NewsListInteractorOutput {
    func fetchNewsListSuccess(newsList: [News]) {
        self.view?.show(newsList: newsList)
    }

    func fetchNewsListFailure(error: Error?) {
        // show Error
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;View&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

final class NewsListViewController: UIViewController, NewsListView {

    private let presenter: NewsListPresenter

    init(presenter: NewsListPresenter) {
        self.presenter = presenter

        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        presenter.viewDidLoad(view: self)
    }

    func show(newsList: [News]) {
        // show the news in the UI 
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, we are fetching the news list from the &lt;strong&gt;interactor&lt;/strong&gt; layer, then update the &lt;strong&gt;presenter&lt;/strong&gt; with the result and the presenter is prepare the data for the View and boom pass it&lt;/p&gt;

&lt;p&gt;Last piece from the puzzle here is to build our module, so I have created a builder class to launch my module&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;final class NewsListBuilder {&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func build() -&amp;amp;gt; UIViewController {
    let router = NewsListRouterImplementation()
    let repo = NewsListRepoImplementation()
    let interactor = NewsListInteractor(repo: repo)
    let presenter = NewsListPresenterImplementation(router: router, interactor: interactor)
    let view = NewsListViewController(presenter: presenter)

    router.viewController = view
    interactor.output = presenter
    return view
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;}&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;VIPER is sounds complex in the beginning but it’s very clean architecture. It isolates each module from others. So changing or fixing bugs is very easy as you only have to update a specific module. Also for having a modular approach VIPER creates a very good environment for unit testing. As each module is independent of others, it maintains low coupling very well. So, dividing work among co-developers is also pretty simple.&lt;/p&gt;

&lt;p&gt;My advice if you are going to using VIPER in your project, the smartest thing would be to use an automatic module structure generator. Otherwise creating files for modules will be a big hustle, There are few generators available online.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/pepibumur/viper-module-generator?utm_source=swifting.io&amp;amp;utm_medium=web&amp;amp;utm_campaign=blog%20post" rel="noopener noreferrer"&gt;VIPER Gen &lt;/a&gt;&lt;br&gt;
&lt;a href="https://github.com/iSame7/ViperCode?utm_source=swifting.io&amp;amp;utm_medium=web&amp;amp;utm_campaign=blog%20post" rel="noopener noreferrer"&gt;VIPER Code&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thank you for reading! If you liked this article, please Like so other people can read it too :)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Happy coding ✌️&lt;/p&gt;

&lt;p&gt;Reach me out &lt;a href="https://marwanayman.com/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ios</category>
      <category>swift</category>
      <category>viper</category>
      <category>mobile</category>
    </item>
  </channel>
</rss>
