<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saroj Raut on Medium]]></title>
        <description><![CDATA[Stories by Saroj Raut on Medium]]></description>
        <link>https://medium.com/@sarojraut?source=rss-9345e7e2bad6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3qdCu-O_oA6j2zoq.</url>
            <title>Stories by Saroj Raut on Medium</title>
            <link>https://medium.com/@sarojraut?source=rss-9345e7e2bad6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:24:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarojraut/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding the BLoC Pattern in Flutter]]></title>
            <link>https://medium.com/crazy-minds/understanding-the-bloc-pattern-in-flutter-2b9214602bc6?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b9214602bc6</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 18:02:50 GMT</pubDate>
            <atom:updated>2024-12-13T06:50:28.896Z</atom:updated>
            <content:encoded><![CDATA[<p>The BLoC (Business Logic Component) pattern is a state management solution that separates business logic from the user interface in Flutter. It was introduced by Google to create reactive and event-driven applications that are scalable and maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*j9Lb67solqGSi5topeG_IQ.png" /></figure><h3>Key Components of BLoC</h3><ol><li><strong>Events</strong>: Represent user interactions or actions that initiate a change in the state.</li><li><strong>States</strong>: Represent the current state of the application.</li><li><strong>BLoC</strong>: The class that receives events and emits corresponding states.</li></ol><p>Let’s see how BLoC pattern works with a practical example.</p><h3>A Real-World Example of BLoC Design Pattern</h3><p>Below is an example of a simple “Todo List” application built using BLoC pattern. The app allows user to fetch todos and add todos.</p><h4>1. Events</h4><p>These represent the actions that the user performs, such as adding a new todo or fetching todos.</p><pre>// Events<br>import &#39;package:equatable/equatable.dart&#39;;<br><br>class TodoEvent extends Equatable {<br>  const TodoEvent();<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [];<br>}<br><br>class FetchTodosEvent extends TodoEvent {<br>  const FetchTodosEvent();<br>}<br><br>class AddTodoEvent extends TodoEvent {<br>  final String text;<br><br>  const AddTodoEvent(this.text);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [text];<br>}</pre><h4>2. State</h4><p>These represent the current state of the application. For example, loading, loaded, or error states.</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>class TodoState extends Equatable {<br>  const TodoState();<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [];<br>}<br><br>class TodoLoadingState extends TodoState {<br>  const TodoLoadingState();<br>}<br><br>class TodoLoadedState extends TodoState {<br>  final List&lt;String&gt; todos;<br><br>  const TodoLoadedState(this.todos);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [todos];<br>}<br><br>class TodoErrorState extends TodoState {<br>  final String error;<br><br>  const TodoErrorState(this.error);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [error];<br>}</pre><h4>3. BLoC</h4><p>The TodoBloc class listens for incoming events and emits new states accordingly. It handles two events:</p><ul><li><strong>AddTodoEvent</strong>: Adds a new todo to the list.</li><li><strong>FetchTodosEvent</strong>: Simulated API Call: Fetch Todos.</li></ul><pre>class TodoBloc extends Bloc&lt;TodoEvent, TodoState&gt; {<br>  TodoBloc() : super(TodoLoadingState()) {<br>    on&lt;FetchTodosEvent&gt;(_onFetchTodos);<br>    on&lt;AddTodoEvent&gt;(_onAddTodo);<br>  }<br><br>  // Handle FetchTodosEvent<br>  Future&lt;void&gt; _onFetchTodos(FetchTodosEvent event, Emitter&lt;TodoState&gt; emit) async {<br>    emit(TodoLoadingState()); // Emit loading state<br>    try {<br>      await Future.delayed(Duration(seconds: 2)); // Simulate network delay<br>      // Simulated response<br>      emit(TodoLoadedState([&#39;Buy groceries&#39;, &#39;Walk the dog&#39;])); <br>    } catch (error) {<br>      emit(TodoErrorState(&#39;Failed to load todos&#39;)); <br>    }<br>  }<br><br>  // Handle AddTodoEvent<br>  Future&lt;void&gt; _onAddTodo(AddTodoEvent event, Emitter&lt;TodoState&gt; emit) async {<br>    try {<br>      await Future.delayed(Duration(seconds: 2)); // Simulate network delay for adding a todo<br>      // Simulated updated list response<br>      emit(TodoLoadedState([&#39;Buy groceries&#39;, &#39;Walk the dog&#39;, event.text]));<br>    } catch (error) {<br>      emit(TodoErrorState(&#39;Failed to add todo&#39;));<br>    }<br>  }<br>}</pre><h4>4. Model</h4><p>The Todo class represents each todo in the list. It includes an id, text, and a isDone property to track the completion status.</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>class Todo extends Equatable {<br>  final String id;<br>  final String text;<br>  final bool isDone;<br><br>  Todo({<br>    required this.id,<br>    required this.text,<br>    this.isDone = false,<br>  });<br><br>  Todo copyWith({String? id, String? text, bool? isDone}) {<br>    return Todo(<br>      id: id ?? this.id,<br>      text: text ?? this.text,<br>      isDone: isDone ?? this.isDone,<br>    );<br>  }<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [id, text, isDone];<br>}</pre><h4>5. UI</h4><p>Finally, the UI uses BlocProvider and BlocBuilder to interact with the BLoC. The BlocProvider provides the TodoBloc to the widget tree, and the BlocBuilder listens for state changes to update the UI.</p><pre>class TodoListScreen extends StatelessWidget {<br>  final TextEditingController _controller = TextEditingController();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Todo List&#39;),<br>        centerTitle: true,<br>      ),<br>      body: BlocProvider(<br>        create: (context) =&gt; TodoBloc()..add(FetchTodosEvent()), // Fetch todos on screen load<br>        child: Column(<br>          children: [<br>            Padding(<br>              padding: const EdgeInsets.all(16.0),<br>              child: Row(<br>                children: [<br>                  Expanded(<br>                    child: TextField(<br>                      controller: _controller,<br>                      decoration: InputDecoration(<br>                        hintText: &#39;Enter a new todo&#39;,<br>                        border: OutlineInputBorder(),<br>                      ),<br>                    ),<br>                  ),<br>                  SizedBox(width: 10),<br>                  ElevatedButton(<br>                    onPressed: () {<br>                      if (_controller.text.isNotEmpty) {<br>                        context.read&lt;TodoBloc&gt;().add(<br>                          AddTodoEvent(_controller.text),<br>                        );<br>                        _controller.clear();<br>                      }<br>                    },<br>                    child: Icon(Icons.add),<br>                  ),<br>                ],<br>              ),<br>            ),<br>            Expanded(<br>              child: BlocBuilder&lt;TodoBloc, TodoState&gt;(<br>                builder: (context, state) {<br>                  if (state is TodoLoadingState) {<br>                    return Center(child: CircularProgressIndicator());<br>                  } else if (state is TodoErrorState) {<br>                    return Center(child: Text(state.error));<br>                  } else if (state is TodoLoadedState) {<br>                    return ListView.builder(<br>                      itemCount: state.todos.length,<br>                      itemBuilder: (context, index) {<br>                        return ListTile(<br>                          title: Text(state.todos[index]),<br>                        );<br>                      },<br>                    );<br>                  }<br>                  return SizedBox.shrink();<br>                },<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Key Concepts:</h3><ul><li>The <strong>UI</strong> dispatches an <strong>event</strong> (e.g., button press, data fetch).</li><li>The <strong>BLoC</strong> receives the event, processes it (e.g., makes an API call, processes data), and <strong>emits</strong> a new state.</li><li>The <strong>UI</strong> listens for state changes and updates based on the current state.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b9214602bc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/understanding-the-bloc-pattern-in-flutter-2b9214602bc6">Understanding the BLoC Pattern in Flutter</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Generics in Swift?]]></title>
            <link>https://medium.com/crazy-minds/what-are-generics-in-swift-5010375f5e64?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5010375f5e64</guid>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 07:03:53 GMT</pubDate>
            <atom:updated>2024-09-26T14:41:14.192Z</atom:updated>
            <content:encoded><![CDATA[<p>Generics are a feature of Swift which allow for the writing of reusable functions that can work with any type of argument passed to them. Your code does not have to be designed in a redundant manner to work with different types.A generic uses a single upper case letter T instead of having to declare what kind of data it will replace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wekigg9ptKLfMjdNBUCBJw.jpeg" /></figure><h3>Why Go For Generics?</h3><ol><li><strong>Flexibility</strong>: Generics extend the functional and type dimensions of a function by enabling it to be applied to any data.</li><li><strong>Reusability</strong>: Code reusability is enhanced in that there is no need to replicate code for additional types.</li><li><strong>Type safety</strong>: Generics ensure that your code is type-safe by reducing the number of casts at run time. If your program is well formulated at the time of compilation, there will be no errors at run time.</li></ol><h3>Examples uses of Generics in Swift</h3><h4>1. Simple Generic Function</h4><pre>func getMinimum&lt;T: Comparable&gt;(_ a: T, _ b: T) -&gt; T {<br>    return a &lt; b ? a : b<br>}<br><br>// Usage<br>let minInt = getMinimum(10, 20)        // Output: 10<br>let minString = getMinimum(&quot;apple&quot;, &quot;banana&quot;)  // Output: &quot;apple&quot;</pre><p>In this example, the getMinimum function accepts inputs of any type and returns an output of the same type using the generic type T, demonstrating the flexibility and usefulness of type T.</p><p>Similarly, now lets move to some more common examples in swift</p><h4>2. Generic API Service</h4><p>Generics are commonly used in networking libraries like Alamofire or for building type-safe networking layers.</p><p>For example,here is a generic APIService that could handle responses of different types.</p><pre>struct APIService {<br>    func fetchData&lt;T: Decodable&gt;(from url: URL, completion: @escaping (Result&lt;T, Error&gt;) -&gt; Void) {<br>        URLSession.shared.dataTask(with: url) { data, _, error in<br>            if let error = error {<br>                completion(.failure(error))<br>                return<br>            }<br>            guard let data = data else { return }<br>            do {<br>                let decodedData = try JSONDecoder().decode(T.self, from: data)<br>                completion(.success(decodedData))<br>            } catch {<br>                completion(.failure(error))<br>            }<br>        }.resume()<br>    }<br>}</pre><p>In this example, T is a placeholder for any type. When the function is called, the compiler determines what actual type Tshould be based on the types of the arguments.</p><p>Now assume we have a model.</p><pre>struct User: Decodable {<br>    let id: Int<br>    let name: String<br>    let email: String<br>}<br></pre><p>Now, you can create an instance of APIService and call the fetchData method with the appropriate URL.</p><pre>let apiService = APIService()<br><br>// Example URL <br>guard let url = URL(string: &quot;https://example.com/api/user&quot;) else { return }<br><br>apiService.fetchData(from: url) { (result: Result&lt;User, Error&gt;) in<br>    switch result {<br>    case .success(let user):<br>        print(&quot;User ID: \(user.id), Name: \(user.name), Email: \(user.email)&quot;)<br>    case .failure(let error):<br>        print(&quot;Error: \(error.localizedDescription)&quot;)<br>    }<br>}</pre><p>In this example:</p><ul><li>User is the model that conforms to Decodable.</li><li>We replace T with User because the API is expected to return a User model upon success. Similarly, the same function can be used to fetch different types of models like Product, Order, etc., if the API returns other models.</li></ul><h4>3. <strong>Generic viewModel</strong></h4><p>Generics can be used to create reusable and flexible view models, especially in apps with different kinds of data.</p><p>For example ,here is a generic view model can work with any model type:</p><pre>class ViewModel&lt;T&gt; {<br>    var items: [T] = []<br>    <br>    init(items: [T]) {<br>        self.items = items<br>    }<br>    <br>    func numberOfItems() -&gt; Int {<br>        return items.count<br>    }<br>    <br>    func item(at index: Int) -&gt; T {<br>        return items[index]<br>    }<br>}<br><br>let stringViewModel = ViewModel(items: [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;])<br>let numberViewModel = ViewModel(items: [1, 2, 3, 4])</pre><h3>In Summary</h3><p>Generics in Swift assist in writing more robust code which is reusable with any of the data types . It prevents you from code duplication, allows you to keep it tidy, and guarantees type safety. Whether you are working on the networking of your app, its user interface components, or even any other application area, it improves its flexibility and ease of use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5010375f5e64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/what-are-generics-in-swift-5010375f5e64">What Are Generics in Swift?</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to MVVM in SwiftUI]]></title>
            <link>https://medium.com/crazy-minds/beginners-guide-to-mvvm-in-swiftui-702c978dbc15?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/702c978dbc15</guid>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 14:41:11 GMT</pubDate>
            <atom:updated>2024-09-12T17:28:44.030Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is MVVM?</strong></h3><p>MVVM (Model-View-ViewModel) is a design pattern that makes development smoother, reduce bugs ,increase testability and provides flexibility by allowing you to change functionality easily.</p><p>In MVVM, we have three main layers and they are</p><ul><li><strong>Model</strong>: The data layer.</li><li><strong>ViewModel</strong>: The layer that prepares data for display in the View and handles user interactions.</li><li><strong>View</strong>: The UI layer, responsible for displaying the data and responding to user input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgqUDEaAe6_hm5DycMW7BQ.png" /></figure><p>For Example</p><p>Let’s create a screen that displays a list of movies fetched from a API and shows details following MVVM design pattern.</p><h4>Model: Movie</h4><p>The Movie struct represents the movie data in our app.</p><pre>struct Movie {<br>    let id: Int<br>    let title: String<br>    let description: String<br>    let releaseDate: String<br>}</pre><h4>ViewModel: MovieViewModel</h4><p>The MovieViewModel handles the logic of fetching movies and formatting them for the View.</p><pre>import Combine<br><br>class MovieViewModel: ObservableObject {<br>    // Published property to notify the View when data changes<br>    @Published var movies: [Movie] = []<br>    <br>    // Mocked API function to simulate fetching movies<br>    func fetchMovies() {<br>        let sampleMovies = [<br>            Movie(id: 1, title: &quot;Inception&quot;, description: &quot;A mind-bending thriller&quot;, releaseDate: &quot;2010&quot;),<br>            Movie(id: 2, title: &quot;Interstellar&quot;, description: &quot;Exploring space and time&quot;, releaseDate: &quot;2014&quot;),<br>            Movie(id: 3, title: &quot;The Dark Knight&quot;, description: &quot;A gritty superhero saga&quot;, releaseDate: &quot;2008&quot;)<br>        ]<br>        <br>        // Assigning mock data to the movies array<br>        self.movies = sampleMovies<br>    }<br>}</pre><h4>View: MovieListView</h4><p>The MovieListView is responsible for displaying the list of movies and updating the UI when the ViewModel&#39;s data changes.</p><pre>import SwiftUI<br><br>struct MovieListView: View {<br>    // Observing the ViewModel<br>    @ObservedObject var viewModel = MovieViewModel()<br>    <br>    var body: some View {<br>        NavigationView {<br>            List(viewModel.movies, id: \.id) { movie in<br>                VStack(alignment: .leading) {<br>                    Text(movie.title)<br>                        .font(.headline)<br>                    Text(&quot;Release Date: \(movie.releaseDate)&quot;)<br>                        .font(.subheadline)<br>                }<br>            }<br>            .navigationTitle(&quot;Movies&quot;)<br>            .onAppear {<br>                viewModel.fetchMovies()  // Fetch movies when the view appears<br>            }<br>        }<br>    }<br>}</pre><h3>Benefits of Using MVVM in This Example</h3><h4>1. Separation of Concerns</h4><p>Each layer is focused on a specific task, making it easier to modify or extend without affecting the other parts.</p><h4>2. Testability</h4><p>You can test the ViewModel and ensures that the business logic works as expected, even without the View.</p><p>For example:</p><pre>import XCTest<br>@testable import YourApp<br><br>class MovieViewModelTests: XCTestCase {<br>    func testFetchMovies() {<br>        let viewModel = MovieViewModel()<br>        viewModel.fetchMovies()<br>        <br>        XCTAssertEqual(viewModel.movies.count, 3)<br>        XCTAssertEqual(viewModel.movies[0].title, &quot;Inception&quot;)<br>    }<br>}</pre><h4>3. Reusability</h4><p>You can share ViewModel logic across multiple screens or features, reducing redundancy.</p><h4>4. Easier Maintenance</h4><p>The MVVM pattern makes it easier to update or change logic in a single place, reducing the chance of introducing bugs in other parts of the app.</p><h4>5. Scalability</h4><p>The clean separation of responsibilities makes it easier to introduce new features as your app grows in complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=702c978dbc15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/beginners-guide-to-mvvm-in-swiftui-702c978dbc15">Beginner’s Guide to MVVM in SwiftUI</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is @escaping and @nonescaping closures in Swift?]]></title>
            <link>https://medium.com/crazy-minds/what-is-escaping-and-nonescaping-closures-in-swift-666d3e7010df?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/666d3e7010df</guid>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 15:47:51 GMT</pubDate>
            <atom:updated>2024-11-20T12:42:25.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5wX2kEDgsSobQWFpu0BDg.png" /></figure><p>In Swift, closures is of two types based on how and when they are used: <strong>escaping</strong> and <strong>non-escaping</strong> closures.</p><p>Understanding the difference between escaping and non-escaping closures is important for managing memory properly. Let’s understand them in detail</p><h3>1) @nonescaping Closure</h3><p>A <strong>non-escaping closure</strong> is the default behavior in Swift. There’s no need to worry about memory management issues like capturing selfweakly because non-escaping closures are used for tasks where the closure will run immediately within the function, such as in synchronous operations.</p><p>For example:</p><pre>func performTask(completion: () -&gt; Void) {<br>    // The closure is executed immediately<br>    print(&quot;Task started&quot;)<br>    completion()<br>    print(&quot;Task ended&quot;)<br>}<br><br>performTask {<br>    print(&quot;Completion called&quot;)<br>}</pre><h4>Characteristics:</h4><ul><li><strong>Synchronous</strong>: Non-escaping closures are executed immediately within the function’s body.</li><li><strong>Memory Management</strong>: Since they do not escape the function, there’s no risk of retain cycles in the function’s self.</li></ul><h3>1) @escaping Closure</h3><p>An <strong>escaping</strong> <strong>closure</strong> is a closure that is executed after the function it was passed to has returned.A common example of an escaping closure is a completion handler, which might run at some point in the future, depending on the task’s completion. When a task takes a while to complete, such as a <strong>network request or a long-running computation</strong>, the closure <strong>“escapes”</strong> the function’s execution context and is called later.</p><p>In the <strong>escaping</strong> closure,[weak self] is used to avoid a strong reference cycle between self and the closure and manage memory effectively.</p><p>For Example</p><pre><br>// ApiService.swift<br>class ApiService {<br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>        // Simulation of an API call<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            completion(.success(&quot;Data from API&quot;))<br>        }<br>    }<br>}<br><br>// SomeClass.swift<br>class SomeClass {<br>    private var apiService: ApiService<br>    var data: String?<br><br>    init(apiService: ApiService) {<br>        self.apiService = apiService<br>    }<br><br>    func getData() {<br>        apiService.fetchData { [weak self] result in // using weak self to avoid strong reference cycle on escaping cloure<br>            switch result {<br>            case .success(let fetchedData):<br>                print(&quot;Received data: \(fetchedData)&quot;)<br>                self?.data = fetchedData<br>            case .failure(let error):<br>                print(&quot;Error fetching data: \(error)&quot;)<br>            }<br>        }<br>    }<br>}<br></pre><h4>Characteristics:</h4><ul><li><strong>Asynchronous</strong>: Escaping closures are used in asynchronous operations, such as network requests or background tasks.</li><li><strong>Memory Management</strong>: Because they can executed even after the self is deallocated from memory, so you need to use [weak self] in the closure helps prevent memory leaks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666d3e7010df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/what-is-escaping-and-nonescaping-closures-in-swift-666d3e7010df">What is @escaping and @nonescaping closures in Swift?</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginners guide to Dependency Injection in Swift]]></title>
            <link>https://medium.com/crazy-minds/a-beginners-guide-to-dependency-injection-in-swift-7b559c6c793e?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b559c6c793e</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 08:31:55 GMT</pubDate>
            <atom:updated>2024-09-11T15:55:14.219Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first heard about Dependency Injection, I thought it was an advanced technique, and doubted if it was worth the effort since my code seemed to work fine without it. However, after trying it out, I realised it’s actually a simple and straightforward implementation with huge benefits</p><p>The main idea of dependency injection is passing dependencies explicitly instead of creating them directly within a class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*pvNi2caDrSKfsg968F8TRQ.jpeg" /></figure><p>For example lets see below code</p><h3>Without Dependency Injection</h3><pre>// ApiService.swift<br>class ApiService {<br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>        // Simulation of an API call<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            completion(.success(&quot;Data from API&quot;))<br>        }<br>    }<br>}<br><br>// MyViewModel.swift<br>class MyViewModel {<br>    private let apiService: ApiService<br>    <br>    init() {<br>        self.apiService = ApiService() // Direct instantiation<br>    }<br>    <br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        apiService.fetchData { result in<br>            switch result {<br>            case .success(let data):<br>                completion(data)<br>            case .failure:<br>                completion(nil)<br>            }<br>        }<br>    }<br>}<br><br>// MyViewController.swift<br>class MyViewController: UIViewController {<br>    private var viewModel: MyViewModel!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        viewModel = MyViewModel() // Direct instantiation<br>        viewModel.loadData { data in<br>            print(&quot;Received data: \(data ?? &quot;No data&quot;)&quot;)<br>        }<br>    }<br>}</pre><h4>Issues:</h4><ul><li><strong>Tight Coupling:</strong> MyViewModel is tightly coupled with ApiService, making it hard to substitute a different implementation (e.g., for testing).</li><li><strong>Hard to Test:</strong> Testing MyViewModel in isolation is difficult because you cannot easily mock or stub ApiService.</li></ul><h3>With Dependency Injection</h3><p>In this version, ViewModel receives its dependencies through the initializer, improving testability and flexibility.</p><pre>// ApiService.swift<br>protocol ApiServiceProviding {<br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void)<br>}<br><br>class ApiServiceProvider: ApiServiceProviding {<br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>        // Simulate an API call<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            completion(.success(&quot;Data from API&quot;))<br>        }<br>    }<br>}<br><br>// MyViewModel.swift<br>class MyViewModel {<br>    private let apiService: ApiServiceProviding<br>    <br>    init(apiService: ApiServiceProviding) {<br>        self.apiService = apiService // Dependency Injection<br>    }<br>    <br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        apiService.fetchData { result in<br>            switch result {<br>            case .success(let data):<br>                completion(data)<br>            case .failure:<br>                completion(nil)<br>            }<br>        }<br>    }<br>}<br><br>// MyViewController.swift<br>class MyViewController: UIViewController {<br>    private var viewModel: MyViewModel!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let apiServiceProvider = ApiServiceProvider() // Create an instance of ApiServiceProvider<br>        viewModel = MyViewModel(apiService: apiServiceProvider) // Inject dependency<br>        <br>        viewModel.loadData { data in<br>            print(&quot;Received data: \(data ?? &quot;No data&quot;)&quot;)<br>        }<br>    }<br>}</pre><h4>Benefits:</h4><p><strong>Loose Coupling:</strong></p><ul><li><strong>Before:</strong> MyViewModel creates an instance of ApiServiceProvider internally.</li><li><strong>After:</strong> MyViewModel depends on ApiServiceProviding, allowing different implementations to be injected. This means MyViewModel can work with any class that conforms to ApiServiceProviding.</li></ul><p><strong>Improved Testability:</strong></p><ul><li><strong>Before:</strong> You cannot easily test MyViewModel in isolation because you need a real instance of ApiServiceProvider.</li><li><strong>After:</strong> You can use a mock implementation of ApiServiceProviding for testing. This makes unit testing easier and more focused.</li></ul><p>For testing, you can inject a mock implementation of ApiServiceProviding.</p><pre>// MockApiService.swift<br>class MockApiService: ApiServiceProviding {<br>    func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>        completion(.success(&quot;Mock data&quot;)) <br>    }<br>}<br><br>// MyViewModelTests.swift<br>import XCTest<br><br>class MyViewModelTests: XCTestCase {<br>    func testLoadData() {<br>        let mockServiceProvider = MockApiServiceProvider()<br>        let viewModel = MyViewModel(apiService: mockServiceProvider)<br>        <br>        let expectation = self.expectation(description: &quot;Data loaded&quot;)<br>        <br>        viewModel.loadData { data in<br>            XCTAssertEqual(data, &quot;Mock data&quot;)<br>            expectation.fulfill()<br>        }<br>        <br>        waitForExpectations(timeout: 1, handler: nil)<br>    }<br>}</pre><p><strong>Enhanced Maintainability:</strong></p><ul><li><strong>Before:</strong> Changes to ApiServiceProvider might require modifications in MyViewModel.</li><li><strong>After:</strong> MyViewModel remains unaffected by changes to ApiServiceProvider as long as it adheres to ApiServiceProviding.</li></ul><p><strong>Flexible Configuration:</strong></p><ul><li><strong>Before:</strong> All configuration and initialization logic for ApiServiceProvider are tied to MyViewModel.</li><li><strong>After:</strong> You can configure and inject different implementations of ApiServiceProviding as needed, providing more flexibility for different contexts or configurations.</li></ul><p>By using Dependency Injection, you achieve a more modular, flexible, and testable codebase, which enhances the overall quality and maintainability of your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b559c6c793e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/a-beginners-guide-to-dependency-injection-in-swift-7b559c6c793e">A beginners guide to Dependency Injection in Swift</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence (AI)]]></title>
            <link>https://medium.com/crazy-minds/artificial-intelligence-ai-17b11240d332?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/17b11240d332</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificalintelligence]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 07:29:38 GMT</pubDate>
            <atom:updated>2024-09-11T14:48:20.296Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial Intelligence (AI) is a rapidly growing field that has the potential to significantly impact every aspect of our lives. From improving healthcare and education to revolutionizing the way we work and interact with technology, the potential applications of AI are virtually limitless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*sTic1IzHr-cUrOBvTrGPeg.jpeg" /></figure><p>AI is defined as the development of computer systems that can perform tasks that typically require human intelligence, such as visual perception, speech recognition, decision-making, and language translation. There are two main types of AI: narrow or weak AI, and general or strong AI. Narrow AI is designed for a specific task and operates within a limited scope, such as Siri or Alexa. On the other hand, strong AI refers to a machine that has the ability to perform any intellectual task that a human can. While strong AI does not yet exist, narrow AI is being integrated into various industries, including healthcare, finance, and customer service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*kXt9kWkDOrviBx3Wg5S1Yg.png" /></figure><p>One of the most promising applications of AI is in the healthcare industry. AI can be used to analyze vast amounts of medical data and provide insights and predictions that can help healthcare professionals make better decisions. For example, AI algorithms can be trained to identify patterns in medical images and accurately diagnose conditions such as skin cancer. AI can also be used to analyze patient data and predict the likelihood of a particular condition or disease, enabling healthcare professionals to intervene early and provide more effective treatment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*0UkEe41xFtpfc5H95CZGXQ.png" /></figure><p>Another area where AI is having a significant impact is in finance. AI algorithms can be trained to analyze vast amounts of financial data and provide insights and predictions that can help financial professionals make better decisions. For example, AI can be used to analyze stock market trends and provide predictions about which stocks are likely to perform well in the future. AI can also be used to detect fraud and other financial crimes, improving the overall security of the financial system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByZs4zPWoe2DYVpKnFr38g.jpeg" /></figure><p>The use of AI in customer service is also growing rapidly. AI chatbots are being used to provide quick and efficient customer service, answering common questions and providing assistance 24/7. AI-powered virtual assistants are also being developed to provide personalized recommendations and support, improving the overall customer experience.</p><p>One of the biggest benefits of AI is its ability to increase efficiency and accuracy. AI algorithms can process vast amounts of data and make predictions based on that data much faster and more accurately than a human could. This can lead to improved decision-making, faster problem-solving, and increased productivity. For example, AI can be used to analyze data from production processes and identify inefficiencies that can be improved, leading to increased productivity and lower costs.</p><p>Despite its many potential benefits, there are also ethical and societal concerns associated with AI. One concern is the potential loss of jobs as machines and algorithms become capable of performing tasks previously done by humans. This could result in significant job losses, particularly in industries such as manufacturing and customer service. There is also the risk of biased algorithms, where AI algorithms make decisions based on biased data or algorithms, leading to discriminatory outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM1iQhSjNNKRWoqRHZnBrA.jpeg" /></figure><p>Another concern is the danger of AI being used maliciously, such as in autonomous weapons. As AI becomes more advanced, there is the risk that it could be used to develop weapons that can operate without human intervention, leading to the potential for unintended consequences and loss of life.</p><p>To ensure that AI is developed and used ethically, it is important to establish regulations and guidelines for its development and deployment. The field of AI ethics is growing, and organizations such as the Partnership on AI are working to create a framework for responsible AI. This includes ensuring that AI algorithms are transparent and explainable, avoiding the use of biased data, and ensuring that AI is developed and used in a way that benefits all members of society.</p><p>In conclusion, AI has the potential to greatly benefit society, but it must be developed and used responsibly and ethically.</p><p><em>Note: This article was created with the assistance of AI technology to enhance clarity and provide comprehensive insights.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17b11240d332" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/artificial-intelligence-ai-17b11240d332">Artificial Intelligence (AI)</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OTP Field]]></title>
            <link>https://medium.com/crazy-minds/otp-field-836f7a297731?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/836f7a297731</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[otp]]></category>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[one-time-password]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Sat, 23 May 2020 06:54:49 GMT</pubDate>
            <atom:updated>2024-09-12T14:45:41.533Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom OTP Field in iOS:Introducing SROTPView for Seamless Verification</h3><p>There were lots of otp textfields library available in cocoacontrols and github but it was really difficult for us to find the otp field and if found there are lots of bugs and complexity which makes us difficult to use that library. So, I have created a new library to meet most of the Application’s requirements called <a href="https://github.com/sarojraut/SROTPView">SROTPView</a>.</p><h3><strong>Types of Fields used in SROTPView</strong></h3><p>There are currently three different types of OTP field used in this library and they are :</p><p><strong>Underlined OTP Field</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jo06Eh9VtxwwWccSH9mPpA.png" /></figure><p><strong>Bordered OTP Field</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_hybZbffKnqqKojSuIQSIw.png" /></figure><p><strong>Round OTP Field</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YDQzNxHk3yaso56ShNpeEA.png" /></figure><p>These otp fields support copy paste feature and gets otp from message easily.</p><p><strong>Filled OTP Field</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*NdITJHBN2bFzVEX5YAjBww.png" /></figure><p>These otp fields support filled and unfilled feature</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=836f7a297731" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/otp-field-836f7a297731">OTP Field</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</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 use Realm ,Alamofire, ObjectMapper together ?]]></title>
            <link>https://medium.com/crazy-minds/how-to-use-realm-alamofire-objectmapper-together-38736ea645b2?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/38736ea645b2</guid>
            <category><![CDATA[alamofire]]></category>
            <category><![CDATA[realmswift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[objectmapper]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Fri, 15 Nov 2019 05:40:28 GMT</pubDate>
            <atom:updated>2019-11-15T05:40:28.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Realm ,Alamofire, ObjectMapper together ?</h3><blockquote>Here is the <a href="https://github.com/sarojraut/Test-Project">Github Link</a> of the project I have created to let you understand basic usage of realm , objectmapper and alamofire together. Project use VIP architecture.</blockquote><h3><strong>1) What is Realm?</strong></h3><p>The Realm Platform is a combination of noSQL based server and client components connected via a fast and efficient sync protocol to enable real-time, connected apps and services that are responsive and performance irrespective of network status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBAls56nyopZlw7JeNQ4qw.png" /><figcaption>High Level Diagram of the Realm Platform</figcaption></figure><h3><strong>2) What is Alamofire?</strong></h3><p>Alamofire provides an elegant and composable interface to HTTP network requests. It does not implement its own HTTP networking functionality. Instead it builds on top of Apple’s <a href="https://developer.apple.com/documentation/foundation/url_loading_system/">URL Loading System</a> provided by the Foundation framework. At the core of the system is <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a> and the <a href="https://developer.apple.com/documentation/foundation/urlsessiontask">URLSessionTask</a> subclasses. Alamofire wraps these APIs, and many others, in an easier to use interface and provides a variety of functionality necessary for modern application development using HTTP networking.</p><pre>Alamofire.request(&quot;https://httpbin.org/get&quot;)<br>    .responseString { response in<br>        print(&quot;Response String: \(response.value)&quot;)<br>    }<br>    .responseJSON { response in<br>        print(&quot;Response JSON: \(response.value)&quot;)<br>    }</pre><h3><strong>3) What is ObjectMapper?</strong></h3><p>ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from JSON.</p><pre>class User: Mappable {<br>    var username: String?<br>    var age: Int?<br>    var weight: Double!<br>    var array: [Any]?<br>    var dictionary: [String : Any] = [:]<br>    var bestFriend: User?                       // Nested User object<br>    var friends: [User]?                        // Array of Users<br>    var birthday: Date?<br><br>    required init?(map: Map) {<br><br>    }<br><br>    // Mappable<br>    func mapping(map: Map) {<br>        username    &lt;- map[&quot;username&quot;]<br>        age         &lt;- map[&quot;age&quot;]<br>        weight      &lt;- map[&quot;weight&quot;]<br>        array       &lt;- map[&quot;arr&quot;]<br>        dictionary  &lt;- map[&quot;dict&quot;]<br>        bestFriend  &lt;- map[&quot;best_friend&quot;]<br>        friends     &lt;- map[&quot;friends&quot;]<br>        birthday    &lt;- (map[&quot;birthday&quot;], DateTransform())<br>    }<br>}<br><br>struct Temperature: Mappable {<br>    var celsius: Double?<br>    var fahrenheit: Double?<br><br>    init?(map: Map) {<br><br>    }<br><br>    mutating func mapping(map: Map) {<br>        celsius 	&lt;- map[&quot;celsius&quot;]<br>        fahrenheit 	&lt;- map[&quot;fahrenheit&quot;]<br>    }<br>}</pre><p>Convert a JSON string to a model object:</p><pre>let user = User(JSONString: JSONString)</pre><p>Convert a model object to a JSON string:</p><pre>let JSONString = user.toJSONString(prettyPrint: true)</pre><h3><strong>4) How to use Realm , Objectmapper together?</strong></h3><p>ObjectMapper and Realm can be used together. Simply follow the class structure below and you will be able to use ObjectMapper to generate your Realm models:</p><pre>class Model: Object, Mappable {<br>    dynamic var name = &quot;&quot;<br><br>    required convenience init?(map: Map) {<br>        self.init()<br>    }<br><br>    func mapping(map: Map) {<br>        name &lt;- map[&quot;name&quot;]<br>    }<br>}</pre><p>Using above structure you can easily map json to Realm object. Convert a JSON string to a Realm model object using alamofire:</p><pre>Alamofire.request(urlString)<br>    .responseString { response in<br>      <br>    .responseJSON { response in<br>       </pre><pre>      let jsonString = String(data: response.data!, encoding: .utf8)!</pre><pre>//parse json to realm object</pre><pre>       let user = Model(JSONString: JSONString)</pre><pre>//store realm object user to database</pre><pre>        let realm = try! Realm()                        <br>           realm.beginWrite()<br>           realm.add(user, update: Realm.UpdatePolicy.modified)</pre><pre>         if realm.isInWriteTransaction {   <br>              try! realm.commitWrite()                      <br>           }<br>       }<br>    }</pre><pre>//To Retrive from database use</pre><pre>let realm = try! Realm()                       <br>let results =  realm.objects(Model.self)<br>print(results)</pre><p>In this way you can easily use realm with objectmapper and parse json to realm object to save and retrive data</p><p>For more detail about its implementation on project, please go to the <a href="https://github.com/sarojraut/Test-Project">Github Link</a> and clone project to see the implementaion of the realm , objectmapper and alamofire together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38736ea645b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/how-to-use-realm-alamofire-objectmapper-together-38736ea645b2">How to use Realm ,Alamofire, ObjectMapper together ?</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VIP (Clean Swift Architecture) In IOS]]></title>
            <link>https://medium.com/crazy-minds/vip-clean-swift-architecture-in-ios-bb1d71680542?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb1d71680542</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 11:58:36 GMT</pubDate>
            <atom:updated>2019-04-02T11:58:36.210Z</atom:updated>
            <content:encoded><![CDATA[<p>I was always curious to try new architecture so that my projects support easy Testability and fix the Massive View Controller problem. VIP is very similar to VIPER as both originated from <a href="https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html">Uncle Bob’s Clean Architecture</a> ideas.After implementing VIP architecture in my project ,I came to know its importance.</p><p>VIP also encourages the use of templates to “facilitate” its implementation.You can find template on <a href="https://clean-swift.com/clean-swift-ios-architecture/">Clean Swift IOS Architecture </a>and more detail about VIP life cycle as well. Using those template you don’t need to worry about the implementation of VIP architecture in your project. Templates helps to write test cases easily.</p><h3>VIP-Unidirectional approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0H5qL1vJlx23nxACCZ54Q.png" /><figcaption>VIP follows Unidirectional approach.</figcaption></figure><h3>VIPER-Bidirectional approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQ4nIxv_PSbxH1QbcEXPuQ.png" /><figcaption>VIPER follows Bidirectional approach</figcaption></figure><p>In the above diagram we can see that VIP architecture follows a unidirectional approach which differs itself from VIPER as it follows Bi-directional approach.Both architecture is based on <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> which leads to a clean architecture and better testability.</p><h3>How to use VIP template in your project</h3><p>First Download the template from <a href="https://clean-swift.com/clean-swift-ios-architecture/">clean swift architecture</a></p><p>Copy the clean swift folder to /Users/&lt;user&gt;/Library/Developer/Xcode/Templates/File\ Templates</p><p>Start Xcode and create a new file (File &gt; New &gt; File or ⌘N)</p><p>Search for Clean Swift section and choose between available templates</p><p>In this way you can start implementing VIP architecture in your project without headache.</p><p>Similarly VIP template has template for Unit testing implementation. As we know that VIP fully support TDD(Test Driven Development).You do not have to worry about writing Unit test Classes for your project.</p><p><a href="https://github.com/sarojraut/VIP-Demo"><strong>VIP-Demo Project</strong></a></p><p>If you are more confuse about its implementation in real life project i have made simple demo regarding <a href="https://github.com/sarojraut/VIP-Demo"><strong><em>VIP Architecture here in Github project</em></strong></a><strong><em> </em></strong>about the implementation in the project as well as Unit test implementation so that you can start follow TDD(Test Driven Development) in the project.</p><h3>VIP Architecture implementation</h3><p>VIP consists of not only three parts.Though its name is only VIP but it has more components than just ViewControllers, Interactors, and Presenters, for example, Data Models, Routers and Workers as well as you can divide Viewcontrollers to Configurator if it start to become massive.</p><h3>ViewController</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d277e2f54e5af3a65a9c22164f7a0810/href">https://medium.com/media/d277e2f54e5af3a65a9c22164f7a0810/href</a></iframe><p>In ViewController ,In viewDidLoad(), we have some business logic to run, so we call fetchPosts(). In fetchPosts(), we invoke fetchPosts(request) on the output (the interactor). That’s it. We ask the output to perform our business logic. The view controller doesn’t and shouldn’t care who and how it is done.But you can divide ViewController to Configurator if it is necessary.</p><h3>Interactor</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff96162c0b7d8105a81950764025c4b/href">https://medium.com/media/3ff96162c0b7d8105a81950764025c4b/href</a></iframe><p>The interactor contains your app’s business logic. The user taps and swipes in your UI in order to interact with your app. The view controller collects the user inputs from the UI and passes it to the interactor. It then retrieves some models and asks some workers to do the work.</p><h3>Worker</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4146e3b1ae7322b05e1cde7e7ce40cce/href">https://medium.com/media/4146e3b1ae7322b05e1cde7e7ce40cce/href</a></iframe><p>A Posts View may need to fetch the Posts from Core Data, makes api request and fetch posts from api, allows users to like post and comment posts , …etc. You don’t want to swamp the interactor with doing all these tasks. Instead, you can break it down into many workers, each doing one thing. You can then reuse the same workers elsewhere.</p><h3>Model</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ad2f92a517ab53cb13c68a4e5a9dd6/href">https://medium.com/media/98ad2f92a517ab53cb13c68a4e5a9dd6/href</a></iframe><p>As we know that while fetching request from api we have request parameters and response and ViewModel to display response to View.Here i have remove ViewModel from model as i am influence by eureka library which keeps ViewModel with View and find it easy to work like that but you can keep ViewModel here.</p><ul><li><strong>Request</strong> — The view controller constructs a request model and passes it to the interactor. A request model contains mostly user inputs, such as text entered in text fields and values chosen in pickers.</li><li><strong>Response</strong> — After the interactor finishes doing work for a request, it encapsulates the results in a response model and then passes it to the presenter.</li><li><strong>View Model</strong> — After the presenter receives the response from the interactor, it formats the results into primitive data types such as String and Int, and stuff them in the view model. It then passes the view model back to the view controller for display.</li></ul><h3>Presenter</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8daf36d4e66efde43481110631657783/href">https://medium.com/media/8daf36d4e66efde43481110631657783/href</a></iframe><p>After the interactor produces some results, it passes the response to the presenter. The presenter then marshal the response into view models suitable for display. It then passes the view models back to the view controller for display to the user.</p><h3>Router</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/172ca51f70a75de4fcbc0fcb64b47434/href">https://medium.com/media/172ca51f70a75de4fcbc0fcb64b47434/href</a></iframe><p>When the user taps the next button to navigate to the next scene in the storyboard, a segue is trigged and a new view controller is presented. A router extracts this navigation logic out of the view controller. It is also the best place to pass any data to the next scene. As a result, the view controller is left with just the task of controlling views.</p><p>In this way you can use VIP architecture and you know that testing is only possible with a sound architecture. So start TDD(Test Driven Development from now onwards).Please Share and let more people know about the importance of this architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1d71680542" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/vip-clean-swift-architecture-in-ios-bb1d71680542">VIP (Clean Swift Architecture) In IOS</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Flutter]]></title>
            <link>https://medium.com/crazy-minds/introduction-to-flutter-d5ac9f62a70?source=rss-9345e7e2bad6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ac9f62a70</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Saroj Raut]]></dc:creator>
            <pubDate>Fri, 22 Mar 2019 04:57:28 GMT</pubDate>
            <atom:updated>2019-03-22T04:57:28.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Various tools have been released for cross-platform development over the years, including web-based tools such as <a href="https://phonegap.com/"><strong>PhoneGap</strong></a> from Adobe, powerful frameworks such as <a href="https://www.xamarin.com/"><strong>Xamarin</strong></a> from Microsoft, and newer tools such as <a href="https://facebook.github.io/react-native/"><strong>React Native</strong></a> from Facebook. A more recent framework to enter the cross-platform arena is <a href="https://flutter.io/"><strong>Flutter</strong></a> from Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEKolqpdm7U487VVaNrEVw.png" /></figure><p>After the release of Flutter Framework i was more excited to know about the development of apps with flutter. When I downloaded app “<a href="https://play.google.com/store/apps/details?id=com.twodimensions.timeline&amp;hl=en">The History of Everything</a>”, I was not so much impressed by the smoothness and stability of app on my device as it crashes on my device while rendering UI. We all know that Native apps are always king of apps but facebook, instagram, uber , etc are some hybrid apps that really makes us think that “Is native is always king?” I am really impressed by React Natives apps like Facebook, Instagram and Uber. Being a IOS developer i found myself in difficult condition for maintaining consistency of apps but while developing apps on flutter we do not have to worry about the consistency and difference between apps. So developing apps with flutter becomes more easy and cheapest.</p><p>As we all know that Flutter features fast development cycles, fast UI rendering and unique UI design, and native app performance on both platforms but regarding smoothness, it need to work a lot.</p><h3>Developing Flutter apps</h3><p>Before start developing flutter apps, developer most know about what are flutter widgets. <strong>Flutter widgets</strong> are built using a modern react-style framework, which takes inspiration from <a href="https://reactjs.org/">React</a>. The central idea is that you build your UI out of widgets. Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, the widget rebuilds its description, which the framework diffs against the previous description in order to determine the minimal changes needed in the underlying render tree to transition from one state to the next.</p><p>Flutter comes with a suite of powerful <strong>basic widgets</strong>, of which the following are very commonly used:</p><ul><li><a href="https://docs.flutter.io/flutter/widgets/Text-class.html">Text</a></li><li><a href="https://docs.flutter.io/flutter/widgets/Row-class.html">Row</a>, <a href="https://docs.flutter.io/flutter/widgets/Column-class.html">Column</a></li><li><a href="https://docs.flutter.io/flutter/widgets/Stack-class.html">Stack</a></li><li><a href="https://docs.flutter.io/flutter/widgets/Container-class.html">Container</a></li></ul><h3>Using Material Components</h3><p>Flutter widgets helps you build apps that follow Material Design. A Material app starts with the<a href="https://docs.flutter.io/flutter/material/MaterialApp-class.html">MaterialApp</a> widget, which builds a number of useful widgets at the root of your app, including a <a href="https://docs.flutter.io/flutter/widgets/Navigator-class.html">Navigator</a>, which manages a stack of widgets identified by strings, also known as “routes”.</p><p>Visual, behavioral, and motion-rich widgets implementing the <a href="https://material.io/guidelines/material-design/introduction.html">Material Design guidelines</a>.</p><ul><li><a href="https://flutter.dev/docs/development/ui/widgets/material#App%20structure%20and%20navigation">App structure and navigation</a></li><li><a href="https://flutter.dev/docs/development/ui/widgets/material#Buttons">Buttons</a></li><li><a href="https://flutter.dev/docs/development/ui/widgets/material#Input%20and%20selections">Input and selections</a></li><li><a href="https://flutter.dev/docs/development/ui/widgets/material#Dialogs,%20alerts,%20and%20panels">Dialogs, alerts, and panels</a></li><li><a href="https://flutter.dev/docs/development/ui/widgets/material#Information%20displays">Information displays</a></li><li><a href="https://flutter.dev/docs/development/ui/widgets/material#Layout">Layout</a></li></ul><p>See more widgets in the <a href="https://flutter.dev/docs/development/ui/widgets/catalog">widget catalog</a>.</p><h3>Support custom platform-specific code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57StX0uvS5MwLnkJt-ZkzA.png" /></figure><p>Flutter uses a flexible system that allows you to call platform-specific APIs whether available in Java or Kotlin code on Android, or in ObjectiveC or Swift code on iOS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ac9f62a70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crazy-minds/introduction-to-flutter-d5ac9f62a70">Introduction to Flutter</a> was originally published in <a href="https://medium.com/crazy-minds">Developer Diaries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>