<?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 Ashwin Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Ashwin Shrestha on Medium]]></description>
        <link>https://medium.com/@ashwinshres?source=rss-47ae0165ed2b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*XxNMaWbrc9YavnoOdho4NA.jpeg</url>
            <title>Stories by Ashwin Shrestha on Medium</title>
            <link>https://medium.com/@ashwinshres?source=rss-47ae0165ed2b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:05:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashwinshres/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[Making an overlapping Stacked image views]]></title>
            <link>https://ashwinshres.medium.com/making-an-overlapping-stacked-image-views-e57fa567aa63?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57fa567aa63</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[custom-component]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 02:40:11 GMT</pubDate>
            <atom:updated>2023-03-05T02:40:11.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*VbeXPCAUSZ_HclXE3pYZaA.png" /></figure><p>This is a short tutorial on making an overlapping stacked image view. Often times when we are working with app relating to social media and networking, we will need to show user listing in form of imge views stacked on top of one another like in image above. In this article, I will show how we can achieve this.</p><p>Few classes we need for this are:</p><ol><li>OverlappingStackedImageFlow : An enum, for the flow of stacked image view whether it’s left to right or right to left.</li></ol><pre>enum OverlappingStackedImageFlow { leftToRight, rightToLeft }</pre><p>2. OverlappingStackedImageConfiguration class for all the configurations to achieve this.</p><pre>class OverlappingStackedImageConfiguration {<br>  final int maxImagesToShow; // even if 100 images provided, how many to show in the view<br>  final double itemSize; // size of each image view<br>  final double itemBorderWidth; // size of border to show around the image<br>  final Color borderColor; // color of border<br>  final bool showsMoreCountLabel; // whether to show the more count label or not<br>  final double offsetPercentage; // to what percentage of overlapping we want to do<br>  final OverlappingStackedImageFlow flow; // flow of the stackview<br>  final TextStyle labelStyle; // style of the label to show<br><br>  const OverlappingStackedImageConfiguration(<br>      {required this.maxImagesToShow,<br>      required this.itemSize,<br>      required this.itemBorderWidth,<br>      required this.borderColor,<br>      this.showsMoreCountLabel = true,<br>      this.offsetPercentage = 0.5,<br>      this.flow = OverlappingStackedImageFlow.rightToLeft,<br>      this.labelStyle = const TextStyle(color: Colors.grey, fontSize: 25)});<br>}</pre><p>3. OverlappingStackedImageView The main widget to show the view, here we provide items which is an array of string urls of images and configuration as in point 2 above.</p><pre>class OverlappingStackedImageView extends StatelessWidget {<br>  final List&lt;String&gt; items;<br>  final OverlappingStackedImageConfiguration configuration;<br>  OverlappingStackedImageView(<br>      {required this.items, required this.configuration, super.key});<br>  List&lt;String&gt; _items = [];<br><br>  @override<br>  Widget build(BuildContext context) {<br>    _setUpImages();<br>    return Row(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        SizedBox(<br>          height: configuration.itemSize,<br>          width: widthOfView,<br>          child: Stack(<br>            children: _getChildren(),<br>          ),<br>        ),<br>        Visibility(<br>          visible: configuration.showsMoreCountLabel,<br>          child: Padding(<br>            padding: const EdgeInsets.only(left: 5, right: 15),<br>            child: Text(<br>              _remainingCountText(),<br>              style: configuration.labelStyle,<br>            ),<br>          ),<br>        )<br>      ],<br>    );<br>  }<br><br>  _setUpImages() {<br>    if (isItemsLessThanMaxToShow) {<br>      _items = items.sublist(0, items.length);<br>      return;<br>    }<br>    _items = items.sublist(0, configuration.maxImagesToShow);<br>    switch (configuration.flow) {<br>      case OverlappingStackedImageFlow.leftToRight:<br>        _items = _items.reversed.toList();<br>        break;<br>      case OverlappingStackedImageFlow.rightToLeft:<br>        break;<br>    }<br>  }<br><br>  String _remainingCountText() {<br>    if (isItemsLessThanMaxToShow) {<br>      return &quot;&quot;;<br>    }<br>    return &quot;+ ${items.length - configuration.maxImagesToShow}&quot;;<br>  }<br><br>  bool get isItemsLessThanMaxToShow {<br>    return items.length &lt; configuration.maxImagesToShow;<br>  }<br><br>  double get widthOfView {<br>    return _items.length == 1<br>        ? configuration.itemSize<br>        : (((_items.length - 1) * singleOffset) + configuration.itemSize);<br>  }<br>  <br>  // provides thge list of image views i.e. Image widgets wrapped by positioned widgets for stack view <br>  List&lt;Widget&gt; _getChildren() {<br>    switch (configuration.flow) {<br>      case OverlappingStackedImageFlow.leftToRight:<br>        double offset = -singleOffset;<br>        int index = -1;<br>        return _items.map((e) {<br>          offset += singleOffset;<br>          index += 1;<br>          return _imagePositioned(<br>              leftOffset: 0, rightOffset: offset, index: index);<br>        }).toList();<br><br>      case OverlappingStackedImageFlow.rightToLeft:<br>        int index = 0;<br>        return _items.map((e) {<br>          double offset = singleOffset * index;<br>          Widget item = _imagePositioned(<br>              leftOffset: offset,<br>              rightOffset: singleOffset * (_items.length - index - 1),<br>              index: index);<br>          index += 1;<br>          return item;<br>        }).toList();<br>    }<br>  }<br>  <br>  // returns a offset based on image size and offset percentage<br>  double get singleOffset {<br>    return configuration.itemSize * configuration.offsetPercentage;<br>  }<br>  <br>  // creates a positioned view inside stack view<br>  Widget _imagePositioned(<br>      {required double leftOffset,<br>      required double rightOffset,<br>      required int index}) {<br>    return Positioned(<br>      top: 0,<br>      bottom: 0,<br>      right: rightOffset,<br>      left: leftOffset,<br>      child: Row(<br>        mainAxisAlignment: MainAxisAlignment.end,<br>        children: [<br>          Container(<br>            clipBehavior: Clip.hardEdge,<br>            decoration: BoxDecoration(<br>                borderRadius: BorderRadius.circular(50),<br>                border: Border.all(<br>                    color: configuration.borderColor,<br>                    width: configuration.itemBorderWidth)),<br>            child: _image(_items[index]),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>  <br>// actual imageWidget in the stacked view<br>  Widget _image(String imageUrl) {<br>    return ClipRRect(<br>      clipBehavior: Clip.hardEdge,<br>      borderRadius: BorderRadius.circular(50),<br>      child: SizedBox(<br>        height: configuration.itemSize -<br>            (configuration.itemBorderWidth *<br>                2.0), // multiplied by 2 as border on 2 sides<br>        width: configuration.itemSize -<br>            (configuration.itemBorderWidth *<br>                2.0), // multiplied by 2 as border on 2 sides<br>        child: Container(<br>          color: Colors.white,<br>          child: Image(<br>            image: NetworkImage(imageUrl),<br>            fit: BoxFit.cover,<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Now where ever you need to show this widget:</p><pre>Column(<br>            crossAxisAlignment: CrossAxisAlignment.center,<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: [<br>              OverlappingStackedImageView(<br>                items: imageUrls(),<br>                configuration: const OverlappingStackedImageConfiguration(<br>                    maxImagesToShow: 5,<br>                    itemSize: 80,<br>                    itemBorderWidth: 2,<br>                    borderColor: Colors.green,<br>                    flow: OverlappingStackedImageFlow.rightToLeft),<br>              ),<br>              const SizedBox(<br>                height: 30,<br>              ),<br>              OverlappingStackedImageView(<br>                items: imageUrls(),<br>                configuration: const OverlappingStackedImageConfiguration(<br>                    maxImagesToShow: 5,<br>                    itemSize: 80,<br>                    itemBorderWidth: 2,<br>                    borderColor: Colors.red,<br>                    flow: OverlappingStackedImageFlow.leftToRight),<br>              ),<br>            ],<br>          )</pre><p>Here in example, i have added both left to right and right to left flow layouts in column to show the overlapping image views.</p><p>The code is concise and self explanatory. If you have any issues, please feel free to write to me. I have also pushed the sample codebase in Github, if you wish to clone it.</p><p><a href="https://github.com/ashwin-shres/overlapping_stacked_image_view">https://github.com/ashwin-shres/overlapping_stacked_image_view</a></p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57fa567aa63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Story of a custom Snackbar]]></title>
            <link>https://ashwinshres.medium.com/story-of-a-custom-snackbar-1521e52ed9fd?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1521e52ed9fd</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[overlay]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-snackbar]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 06:49:40 GMT</pubDate>
            <atom:updated>2023-03-04T06:49:40.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*szzZN9JpZ-SAJ5rk" /><figcaption>Photo by <a href="https://unsplash.com/@roketpik?utm_source=medium&amp;utm_medium=referral">Artur Shamsutdinov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is evident that, we all flutter developers love showing Snackbar`. Yes, it is a great widget to display a brief message after a user performs an action, such as a successful login, an error occurred or an action has been completed and so on. <br>Being one of the most used widget it also has it’s own limitations and complexities as follows:</p><ol><li>It is content dependent i.e. it requires a Scaffold widget in order to work properly. If you’re trying to display a Snackbar outside of a Scaffold widget, it may not work as expected.</li><li>It can be intrusive: Since a Snackbar appears at the bottom of the screen, it can be intrusive and block important content on the screen, especially if the user is using a smaller device.</li><li>Limited display time: By default, a Snackbar is displayed for a short period, usually about 4 seconds, after which it disappears automatically. This can be a limitation when you want to display a message for a longer time or until the user takes some action.</li></ol><p>These are a few that we usually face while working with the snack bar. One issue that I faced recently was the problem of not being able to display it above a modal bottom sheet as stated in limitation 1 above. So I came up with a solution to help myself overcome this situation with the use of overlays.</p><blockquote>In Flutter, an overlay is a widget that provides a way to display content on top of other widgets in the app, regardless of where those widgets are in the widget tree. An overlay is typically used for displaying modal dialogs, tooltips, or other types of floating UI elements that need to appear on top of the rest of the app’s content.</blockquote><p>The Overlay widget is a container widget that can hold multiple child widgets, each of which represents an individual overlay element. You can add and remove child widgets from the overlay dynamically, using the Overlay.of(context).insert() and Overlay.of(context).remove() methods.</p><p>In this article, I will be explaining how I made my own Snackbar implementation using Overlay .</p><p>We need four different things we require:</p><ol><li>snackbar_constants.dart file: The duration, we wish to show a snack bar</li></ol><pre>abstract class SnackbarConstants {<br>  static const snackbarDuration = 3;<br>}</pre><p>2. snackbar_style.dart file: There may be different configuration and decoration of snack bar, for success, error, normal. The code snippet is self explanatory.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>enum SnackbarStyle { error, success, normal }<br><br>extension SnackbarStyleExtension on SnackbarStyle {<br>  Color get displayTitleColor {<br>    switch (this) {<br>      case SnackbarStyle.error:<br>        return Colors.white;<br>      case SnackbarStyle.success:<br>        return Colors.white;<br>      case SnackbarStyle.normal:<br>        return Colors.white;<br>    }<br>  }<br><br>  Color get displayBackgroundColor {<br>    switch (this) {<br>      case SnackbarStyle.error:<br>        return Colors.red;<br>      case SnackbarStyle.success:<br>        return Colors.green;<br>      case SnackbarStyle.normal:<br>        return Colors.black;<br>    }<br>  }<br><br>  bool get isCloseButtonVisible {<br>    switch (this) {<br>      case SnackbarStyle.error:<br>        return false;<br>      case SnackbarStyle.success:<br>        return false;<br>      case SnackbarStyle.normal:<br>        return false;<br>    }<br>  }<br>}</pre><p>3. snackbar_position.dart file: To configure where we want to show the snack bar:</p><blockquote>With this: a top position snack bar can also act as in app notification :)</blockquote><p>4. snackbar_overlay.dart file: This is a class holding a unique identifier for each snack bar item along with the overlay entry.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class SnackbarOverlay {<br>  final String id;<br>  late final OverlayEntry overlay;<br><br>  SnackbarOverlay({<br>    required this.id,<br>  });<br>}</pre><p>5. snackbar_content.dart file: This the actual implementation stateful widget of the snack bar item to show in the screen.</p><pre>class SnackBarContent extends StatefulWidget {<br>  final SnackbarOverlay overlay;<br>  final String message;<br>  final SnackbarStyle style;<br>  final SnackbarPosition position;<br>  final Function(SnackbarOverlay)? onCloseClicked;<br>  const SnackBarContent(<br>      {required this.overlay,<br>      required this.message,<br>      required this.style,<br>      required this.position,<br>      this.onCloseClicked,<br>      super.key});<br><br>  @override<br>  State&lt;SnackBarContent&gt; createState() =&gt; _SnackBarContentState();<br>}</pre><p>We provide few things in the constrcutor of this widget, an overlay object of class SnackbarOverlay , a message text, snackbar style , snackbar position and a function callback when close button in snackbar(overlay) is clicked.</p><pre>class _SnackBarContentState extends State&lt;SnackBarContent&gt; {<br>  bool _showsSnackbar = false;<br>  bool _hasShownSnackbar = false;<br>  Future? overlayRemoveFuture;<br>  @override<br>  void initState() {<br>    super.initState();<br>    Future.delayed(const Duration(milliseconds: 10)).whenComplete(() {<br>      setState(() {<br>        _showsSnackbar = true;<br>      });<br><br>      overlayRemoveFuture = Future.delayed(const Duration(<br>              seconds: SnackbarConstants.snackbarDuration, milliseconds: 510))<br>          .whenComplete(() {<br>        _closeNotification();<br>      });<br>    });<br>  }<br><br>  _closeNotification() {<br>    setState(() {<br>      _showsSnackbar = false;<br>    });<br>    _hasShownSnackbar = true;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedPositioned(<br>      left: 10,<br>      right: 10,<br>      bottom: widget.position == SnackbarPosition.top<br>          ? null<br>          : (_showsSnackbar ? 50 : -100),<br>      top: widget.position == SnackbarPosition.top<br>          ? (_showsSnackbar ? 50 : -100)<br>          : null,<br>      curve: Curves.fastOutSlowIn,<br>      duration: const Duration(milliseconds: 500),<br>      child: ClipRRect(<br>        borderRadius: BorderRadius.circular(10),<br>        child: Material(<br>          color: Colors.transparent,<br>          child: _mainContent(),<br>        ),<br>      ),<br>      onEnd: () {<br>        if (_hasShownSnackbar) {<br>          widget.onCloseClicked?.call(widget.overlay);<br>        }<br>      },<br>    );<br>  }<br><br>  Widget _mainContent() {<br>    return SnackbarMainContent(<br>        style: widget.style,<br>        message: widget.message,<br>        onCloseButtonPressed: () {<br>          overlayRemoveFuture?.ignore();<br>          widget.onCloseClicked?.call(widget.overlay);<br>        });<br>  }<br>}</pre><p>6. snackbar_main_content.dart: This has been created to separate out the actual snack bar design, which may change depending upon the projects itself.</p><pre>class SnackbarMainContent extends StatelessWidget {<br>  final SnackbarStyle style;<br>  final String message;<br>  final Function? onCloseButtonPressed;<br>  const SnackbarMainContent(<br>      {required this.style,<br>      required this.message,<br>      required this.onCloseButtonPressed,<br>      super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      decoration: BoxDecoration(<br>          color: style.displayBackgroundColor,<br>          borderRadius: BorderRadius.circular(15)),<br>      child: Row(<br>        children: [<br>          Expanded(<br>            child: Padding(<br>              padding: const EdgeInsets.only(left: 15, top: 17, bottom: 17),<br>              child: Text(<br>                message,<br>                style: TextStyle(color: style.displayTitleColor),<br>              ),<br>            ),<br>          ),<br>          Visibility(<br>            visible: style.isCloseButtonVisible,<br>            child: IconButton(<br>              onPressed: () {<br>                onCloseButtonPressed?.call();<br>              },<br>              icon: const Icon(Icons.close),<br>              color: style.displayTitleColor,<br>            ),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>7. Finally the main handler which handles this all: snackbar_handler.dart</p><pre>class SnackbarHandler {<br>  final List&lt;SnackbarOverlay&gt; _overlays = [];<br>  static final SnackbarHandler _instance = SnackbarHandler._internal();<br>  factory SnackbarHandler() {<br>    return _instance;<br>  }<br><br>  SnackbarHandler._internal();<br><br>  void showOverlay(BuildContext context,<br>      {required String text,<br>      required SnackbarStyle style,<br>      required SnackbarPosition position}) async {<br>    if (text.isEmpty) {<br>      return;<br>    }<br>    OverlayState? overlayState = Overlay.of(context);<br>    final overlay = SnackbarOverlay(id: const Uuid().v4());<br>    OverlayEntry overlayEntry = OverlayEntry(builder: (context) {<br>      return SnackBarContent(<br>        overlay: overlay,<br>        message: text,<br>        style: style,<br>        position: position,<br>        onCloseClicked: (currentOverlay) {<br>          _removeOverlay(currentOverlay);<br>        },<br>      );<br>    });<br>    overlay.overlay = overlayEntry;<br>    _overlays.add(overlay);<br>    overlayState?.insert(overlayEntry);<br>  }<br><br>  _removeOverlay(SnackbarOverlay overlay) {<br>    overlay.overlay.remove();<br>    _overlays.removeWhere((element) =&gt; element.id == overlay.id);<br>  }<br>}</pre><p>This file will handle all incoming snackbar/toast to display in your screen and closes them and removes from screen as well.</p><p>So, from anywhere where you want to display your toast/snackbar/notification, all you need to do is call:</p><pre>SnackbarHandler().showOverlay(context,<br>        text: text, style: SnackbarStyle.error, position: SnackbarPosition.top);</pre><p>I have the code sample in github as well. Feel free to check it out.</p><p><a href="https://github.com/ashwin-shres/custom_snack_bar">https://github.com/ashwin-shres/custom_snack_bar</a></p><p>This has been a learning experience for me. If you have any questions for me, do let me know in the comments section below. Thank you.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1521e52ed9fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A software engineer learns from Naruto Shippuden, Dattebayo!!!]]></title>
            <link>https://medium.com/swlh/a-software-engineer-learns-from-naruto-shippuden-dattebayo-f6e2be9850c3?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6e2be9850c3</guid>
            <category><![CDATA[naruto]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[naruto-shippuden]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 17:21:26 GMT</pubDate>
            <atom:updated>2021-01-28T12:55:38.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4NLqKB5RkeJLhUN-qrazg.jpeg" /></figure><p>A few years back, a friend of mine asked me, “Do you watch anime? Anime is so lit.” To his this question, I was like, “Am I a child to sit and watch anime? I have way more other works and client software to develop than sit and watch some cartoon.”. Years passed, and a few months back, out of nowhere, I thought about giving it a try and then started watching “Naruto”. As I browsed through the episode list, a freaking 500 episode show, I doubted, if I would be able to complete the whole series.</p><p>For those who don’t know what “Naruto” is, it is a Japanese manga series written and illustrated by Masashi Kishimoto. It tells the story of Naruto Uzumaki, a young ninja who seeks recognition from his peers and dreams of becoming the Hokage, the leader of his village. The story is told in two parts — the first set in Naruto’s pre-teen years, and the second in his teens.</p><p>As I started watching the show, I was intrigued by how the story developed with each passing episode. Not only the story but how each character developed and matured overtime was really fascinating to me. So much so that, I completed the entire 500 episodes within a month (skipping some fillers of course). After completing the whole series, when I looked back at it in retrospect, I feel this series was an art which thankfully I saw and learned so much from.</p><p>Yes, everybody is Naruto’s fan, me too Dattebayo, but I feel there are so many underdogs in the show from whom I learned so much as a software developer, so I decided to write down it as an article.</p><p>Here are some of the things I learned from Naruto Shippuden as a software developer:<br>P.s. The list includes some spoilers, if you have not watched it yet (go watch it 🙂)</p><p><strong>My Ninja way (Naruto Uzumaki)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*X_BqsHOCTlSvv_KxgEQpTQ.jpeg" /></figure><p>Everyone has a way of their life and the way they wish to move forward. I have seen many people who get in the software industry just because they think it is fancy. Some get in because their friends are software developers and some take computer science in their studies because they have seen their seniors/brother or sister being a software developer.</p><p>For some people, software development is just a job, but I feel there needs to be a real passion to develop and it needs to be one’s ninja way. Having a strong belief in your ninja way keeps you in check and helps you track your progress as a software developer towards your goal.</p><p><strong>Hard work beats talent when talent doesn’t work hard (Might Guy &amp; Rock Lee)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*40t5f3S86pHUQevHqajByA.png" /></figure><p>These two teacher-student duos are one of my favorites in the whole show. There is so much to learn from these too. Might Guy who knows very little ninjitsu or genjutsu, along with his student Rock Lee who doesn’t know any ninjitsu or genjutsu, are one of the best users of taijutsu. And this knowledge of taijutsu has come from years and years of training and perseverance they have shown for it. They pushed their body to extreme limits while training to become so much powerful that Madara Uchiha himself declared Might Guy as the strongest shinobi he ever fought.</p><p>What this explains is, that in the software development industry, some people have a natural talent for writing code or architect systems while others don’t. But there are different aspects of the software industry that one can try to find one’s niche. And through sheer hard work and continuous learning one can enhance their knowledge and be better at what they do.</p><p><strong>Patience is the Key (Sakura Haruno)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bfcOr5TtB3mBjyTW9zJSCQ.jpeg" /></figure><p>Sakura, who was always in the shadow of her friends of team 7, initially suffered from a lot of inferiority complex. She always felt that she was the one who dragged her team down in every competition. But later, as the story progressed, she gained her confidence slowly with her patience and will to be better and an equal of other members of her team, she finally achieved that, so much so that she surpassed her mentor Lady Tsunade.</p><p>What this teaches us is, a team comprises members of all skill levels and knowledge. There are times when you feel like you are the one dragging the whole team down in any project and feel if it is even worth it? So what do you do in such situations? You keep reminding yourself like Sakura did, that she will work hard and sooner or later be a fruitful asset to your team.</p><p><strong>Believe in your team (Kakashi Hatake)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VoHGWKvFYl9xpn4YhyVAlg.jpeg" /></figure><p>Kakashi Hatake must be one of the most well-written characters of the whole Naruto Shippuden. He is an example of a real team player and a good leader. When he was assigned sensei of Team 7, he initially was hesitant but, then after that, he never took his responsibility as a burden. He taught his team about how only with strong coordination and faith in each other, can a team succeed. He was very observant of the strengths and weaknesses of each team member and helped them overcome them. He was also looking after his team and never backed down from any problem he faced. He also taught his team what he failed to learn when he was a student.</p><p>In the software industry too, I believe, a team is only as good as its leader. A good team leader helps his/her team grow, understand their weaknesses and help them overcome those. He/she also helps his/her team members improve on their strengths. He/she needs to be the one to take one for the team when the situation demands and never lose faith in the team.</p><p><strong>Your contemporaries are your greatest inspiration (Naruto Uzumaki and Sasuke Uchiha)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OHdLAdCPJCBa4fV7hXP_w.jpeg" /></figure><p>There exist a certain kind of bond between Naruto and Sasuke. They were both friends and foe at the same time, but above all, they were each other’s greatest inspiration. Both Sasuke and Naruto wanted to do better than one another and be at the top from a very early age. Had there not been someone to look at, and have the feeling to be better than the other, I don’t think they would be the greatest shinobis of all time.</p><p>We, as a software developer, can also learn from this. We all need to find someone from our contemporaries to look at and try to push ourselves to be better than them or at least to the level. Healthy competition can be a real motivator to learn and be better than we were yesterday.</p><p>There are so many other characters like Itachi, Hinata, Shikamaru, Nagato, Jiraya, who I loved and learned from, but maybe I will write about them in another post real soon.</p><p>Also, I would like to hear why you like Naruto in the comments down below. 🙂</p><p>P.s. Special thanks to the person who first suggested me to watch Naruto, and yes, I admit, Anime is not just any other cartoon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6e2be9850c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-software-engineer-learns-from-naruto-shippuden-dattebayo-f6e2be9850c3">A software engineer learns from Naruto Shippuden, Dattebayo!!!</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is The Server Down? Send Automated Alerts to Your Team Using Python]]></title>
            <link>https://medium.com/better-programming/server-monitoring-and-sending-alert-to-them-team-when-its-down-using-python-script-cb843084c0a9?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb843084c0a9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 16:44:54 GMT</pubDate>
            <atom:updated>2021-01-22T17:02:08.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is the Server Down? Send Automated Alerts to Your Team Using Python</h3><h4>And create a website monitoring script to track downtimes</h4><figure><img alt="A neon zig-zag arrow pointing to the bottom right" src="https://cdn-images-1.medium.com/max/1024/0*SjA5TQYCoFvUueeD" /><figcaption>Photo by <a href="https://unsplash.com/@ussamaazam?utm_source=medium&amp;utm_medium=referral">Ussama Azam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over the years, I’ve faced many issues where the server is down and the client lets us know. I think many other developers like me have faced similar problems. It doesn’t look good on the software company and developers&#39; part!</p><p>Being an iOS developer with no knowledge of scripting languages like Python, I’ve always felt tied down and I’ve never dared to try them. Yes, there are system monitoring tools available — both open source and paid and those can be used, but integrating another dependency in the system when I just want a simple Email and SMS alert to be sent to the team members when the server is down — I didn’t like that idea.</p><p>I have a Mac mini in my home which is on 24/7 with a stable internet connection, so I thought — why not use it to ping my project’s server every few minutes or an hour and check its status? I decided to sit down and learn a few chunks from here and there to just be able to write the script and run it in cron to alert me when the server goes down.</p><p>I decided to include three things:</p><ul><li>Send all the teammates (including the Project Manager) an email alert with details of when my script is unable to ping the server.</li><li>Send the project manager and team lead an SMS alert.</li><li>Alert me with sound when it is night time (for experimental purposes).</li></ul><p>As I know very little about the language, I decided to take it one step at a time.</p><h3><strong>Step 1: Creating a New Project (Site Monitor)</strong></h3><p>This was easy. I opened terminal, created a new directory for the project and a virtual environment, and then activated it:</p><pre>mkdir sitemonitor<br>cd sitemonitor/<br>python3 -m venv monitor_env<br>source monitor_env/bin/activate</pre><h3><strong>Step 2: Creating the Project Information Structure in a JSON File</strong></h3><p>I need to decide on the basic structure of the project information which I will be needing for the monitor. I needed project name, server URL path to ping to find the status of the server, and then the project members&#39; information: their name, email address (for email alert), and mobile number(for SMS alert). As I would be using a trial Twilio account and decided to make a way for an SMS alert on/off for a project, depending upon the severity of the project, I added another key: send_sms_alert.</p><pre>[<br> {<br>  &quot;server&quot; : &quot;<a href="https://stage.servare.app/">u</a>rl here&quot;,<br>  &quot;project_name&quot;: &quot;project name here&quot;,<br>  &quot;send_sms_alert&quot; : false,<br>  &quot;manager&quot;: {<br>   &quot;name&quot; : &quot;manager name here&quot;,<br>   &quot;email&quot; : &quot;<a href="/service/mailto:ssingh@outcodesoftware.com">m</a>anager email address here&quot;,<br>   &quot;number&quot; : &quot;manager mobile number here&quot;<br>  },<br>  &quot;lead&quot;: {<br>   &quot;name&quot; : &quot;lead name here&quot;,<br>   &quot;email&quot; : &quot;lead email address here&quot;,<br>   &quot;number&quot; : &quot;lead mobile number here&quot;<br>  },<br>  &quot;other_members&quot; : [<br>   {<br>    &quot;name&quot; : &quot;member 1 name here&quot;,<br>    &quot;email&quot; : &quot;<a href="/service/mailto:sshrestha@outcodesoftware.com">m</a>ember 1 email address here&quot;,<br>    &quot;number&quot; : &quot;<a href="/service/mailto:sshrestha@outcodesoftware.com">m</a>ember mobile number here&quot;<br>   }<br>  ]<br> }</pre><pre>]</pre><h3><strong>Step 3: Loading the Projects From JSON File</strong></h3><pre>import json</pre><pre>def check_server_down(project):<br>    # here we ping the server and check it&#39;s status</pre><pre>def load_projects():<br>    f = open(&#39;projects.json&#39;)<br>    projects = json.load(f)<br>    for project in projects:<br>         check_server_down(project)</pre><pre>    f.close()</pre><pre>load_projects()</pre><h3>Step 4: Pinging the Project Server URL to Check its HTTP Response Status Code</h3><p>We assume that we have an endpoint which if the server is up responds with 200 OK always. For this, we need to install the requests library first. But we need to make sure we have the virtual environment activated.</p><pre>(monitor_env) Ashwins-MacBook-Pro:sitemonitor myMac$ pip install requests</pre><p>Now, we call the URL, so inside the method checkServerDown we wrote earlier:</p><pre>import logging<br>import requests<br>import json</pre><pre>def check_server_down(project):<br>    r = requests.get(project[&#39;server&#39;], timeout=timeOutTime)<br> <br>    if r.status_code != 200:<br>        logging.error(&quot;Server down of project {} at   {}&quot;.format(project[&#39;project_name&#39;], datetime.now()))<br>        send_email_alert(project)<br>        if project[&#39;send_sms_alert&#39;]:<br>           send_sms_alert(project)<br>        play_alert()</pre><pre>def load_projects():<br>    f = open(&#39;projects.json&#39;)<br>    projects = json.load(f)<br>    for project in projects:<br>        check_server_down(project)</pre><pre>    f.close()</pre><pre>load_projects()</pre><p>Also for logging purposes, we use the logging module.</p><p>Now as shown above we have three methods: to send an email alert, SMS alert, and play sound alert. We will be writing their implementation next.</p><h3><strong>Step 5: Send Email Alert</strong></h3><p>To send an email alert we need to import the smtplib module and also an smtp service provider. For this example, we’ll be using Gmail as our smtp. For this, however, we need to provide access. So go to the google accounts link that you wish to use as your default email for sending email alerts:</p><p><a href="https://myaccount.google.com/lesssecureapps">https://myaccount.google.com/lesssecureapps</a></p><p>and enable as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*o_5DzGhQ6u2tX_zAqLHBGQ.png" /></figure><pre>import smtplib</pre><pre>smtpEmail = &quot;SMTP_EMAIL_ADDRESS&quot;<br>smtpPassword = &quot;SMTP_PASSWORD&quot;<br>emailFrom = &quot;EMAIL_FROM&quot;</pre><pre>def send_email_alert(project):<br>    conn = smtplib.SMTP(&#39;smtp.gmail.com&#39;,587) # create a new connection<br>    conn.ehlo()<br>    conn.starttls()<br>    conn.login(smtpEmail, smtpPassword)</pre><pre>    projectName = project[&#39;project_name&#39;]<br>    subject = &#39;{} server is down&#39;.format(projectName)</pre><pre>    manager =  project[&#39;manager&#39;]<br>    lead = project[&#39;lead&#39;]</pre><pre>    projectMembers = project[&#39;other_members&#39;]<br>    membersNames = &#39;, &#39;.join(map(str,list(map(lambda x: x[&#39;name&#39;], projectMembers))))<br>    message = &quot;&quot;&quot;The {} project server seems to be down. Please contact your team mates and fix it</pre><pre>       Team members:<br>       Project Manager: {}<br>       Mobile Number: {}</pre><pre>       Team Lead: {}<br>       Mobile Number: {}</pre><pre>       Other Members: <br>       {}</pre><pre>     &quot;&quot;&quot;.format(projectName, manager[&#39;name&#39;], manager[&#39;number&#39;], lead[&#39;name&#39;], lead[&#39;number&#39;], membersNames)</pre><pre>    emailTo = list(map(lambda x: x[&#39;email&#39;], projectMembers))<br>    emailTo.insert(0, lead[&#39;email&#39;])<br>    emailTo.insert(0, manager[&#39;email&#39;])<br>    emailMessage = &#39;Subject: {}\n\n{}&#39;.format(subject, message)<br> <br>    conn.sendmail(emailFrom,emailTo,emailMessage) #sends email<br>    conn.quit() # closes the connection</pre><p>Above, we created an SMTP connection, then created a list of email address from team members, project manager, and project lead and then used those to send an email from emailFrom. In the email body, we added details of all the team members and the project detail.</p><p>After this, I didn’t like the idea of writing the email and password on the script itself so decided to load it from the env file.</p><h3><strong>Step 6: Creating env File for Credentials</strong></h3><p>For this we needed to create a new .env file and add all our credentials there:</p><pre>SMTP_EMAIL_ADDRESS=Email_address_here<br>SMTP_PASSWORD=your_smtp_email_password_here<br>EMAIL_FROM=your_from_email_for_alert_here</pre><p>And then install the python-dotenv library:</p><pre>(monitor_env) Ashwins-MacBook-Pro:sitemonitor myMac$ pip install python-dotenv</pre><p>Now load the credentials to be used from env file:</p><pre>from dotenv import load_dotenv<br>from pathlib import Path<br>import os</pre><pre>env_path = Path(&#39;.&#39;) / &#39;.env&#39;<br>load_dotenv(dotenv_path=env_path)</pre><pre>smtpEmail = os.getenv(&quot;SMTP_EMAIL_ADDRESS&quot;)<br>smtpPassword = os.getenv(&quot;SMTP_PASSWORD&quot;)<br>emailFrom = os.getenv(&quot;EMAIL_FROM&quot;)</pre><h3><strong>Step 7: Send SMS Alert</strong></h3><p>I decided to add an SMS alert to the system, which will be for the project manager and team lead. For this, I created a new Twilio account and got my test Twilio phone number: <a href="http://I decided to add SMS alert too in the system which will be for the project manager and team lead. For this, I created a new Twilio account and got my test Twilio phone number: https://www.twilio.com/login">https://www.twilio.com/login</a></p><p>I installed Twilio library in my project:</p><pre>(monitor_env) Ashwins-MacBook-Pro:sitemonitor myMac$ pip install twilio</pre><p>Next added the Twilio credentials in my env file:</p><pre>TWILIO_SID=TWILIO_SID_HERE<br>TWILIO_AUTH_TOKEN=TWILIO_AUTH_TOKEN_HERE</pre><p>Then added the necessary code to send the SMS alert:</p><pre>from twilio.rest import Client</pre><pre>def send_sms_alert(project):<br>    account_sid = os.getenv(&quot;TWILIO_SID&quot;)<br>    auth_token  = os.getenv(&quot;TWILIO_AUTH_TOKEN&quot;)</pre><pre>    client = Client(account_sid, auth_token)<br>    messageBody = &#39;{} server is down. Please have a look in the system. This auto generated message has been sent to other team members as well. Thank you.&#39;.format(project[&#39;project_name&#39;])</pre><pre>    manager =  project[&#39;manager&#39;]<br>    lead = project[&#39;lead&#39;]</pre><pre>    projectMembers = project[&#39;other_members&#39;]</pre><pre>    mobileNumbers = list(map(lambda x: x[&#39;number&#39;], projectMembers))<br>    mobileNumbers.insert(0, lead[&#39;number&#39;])<br>    mobileNumbers.insert(0, manager[&#39;number&#39;])<br>    mobileNumbers = list(set(mobileNumbers)) # remove the duplicates</pre><pre>    for number in mobileNumbers:<br>      message = client.messages.create(<br>          to=number, <br>          from_=&quot;+19177655746&quot;,<br>          body=messageBody)<br></pre><h3><strong>Step 8: Play Sound Alert</strong></h3><p>Just learning purposes, I decided to also add sound-playing functionality when the server is down. For this, I added the simpleaudio library:</p><pre>(monitor_env) Ashwins-MacBook-Pro:sitemonitor myMac$ pip install simpleaudio</pre><p>Now to play a sound, I added an alert:</p><pre>import simpleaudio as sa</pre><pre>filename = &#39;RedAlert.wav&#39;<br>wave_obj = sa.WaveObject.from_wave_file(filename)</pre><pre>def play_alert():<br>    play_obj = wave_obj.play()<br>    play_obj.wait_done()</pre><p>This completes our script, which now sends an email, SMS, and plays audio when the server is down for a project. Now we need a script which is executed every few minutes or hours using a cron job.</p><h3><strong>Step 9: Shell Script for cron Job</strong></h3><p>For this, we create a shell script on the same directory of the project with the name cronjob.sh:</p><pre>#!/bin/bash</pre><pre>cd /Users/myMac/Documents/sitemonitor<br>source monitor_env/bin/activate<br>python monitor.py</pre><p>This script needs to be made executable with the following command:</p><pre>Ashwins-MacBook-Pro:sitemonitor myMac$ chmod 777 cronjob.sh</pre><p>The above command makes the file cronjob.sh readable, writeable, and executable:</p><pre>Ashwins-MacBook-Pro:sitemonitor myMac$ ls -l<br>-rwxrwxrwx@ 1 myMac  staff     134 Jan 19 18:56 cronjob.sh</pre><p>For more details see: <a href="https://en.wikipedia.org/wiki/Chmod">https://en.wikipedia.org/wiki/Chmod</a></p><h3><strong>Step 10: Adding a New cron Job</strong></h3><p>On Unix-like operating systems, the crontab command opens the cron table for editing. The cron table is the list of tasks scheduled to run at regular time intervals on the system.</p><p>Some of the basic crontab commands:</p><pre>&gt; crontab -l <br>this lists all the cron job in the system</pre><pre>&gt; crontab -r<br>this removes all the cron job in the system</pre><pre>&gt; crontab -e<br>this creates a new cron job in the system</pre><p>Now since we need to add a new cron job for our executable script, that gets executed every 10 minutes:</p><pre>Ashwins-MacBook-Pro:sitemonitor myMac$ crontab -e</pre><p>This opens your vim editor, where you write the following:</p><pre>10 * * * * /Users/myMac/Documents/sitemonitor/cronjob.sh &gt;&gt; /Users/myMac/Documents/sitemonitor/cronError.txt 2&gt;&amp;1</pre><p>Next, press Esc and then wq and hit enter, as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*18fvcda35LTVCV270IhrFw.png" /></figure><p>Now if we go and list cron jobs, it will show this result:</p><pre>Ashwins-MacBook-Pro:sitemonitor myMac$ crontab -l</pre><p>That’s all we need to do — the cronjob is now executed every 10 minutes.</p><h3><strong>Step 11: Making cron Job Run in MacOS (Catalina and Above)</strong></h3><p>For mac users with Catalina or above, the job will not be executed because of Mac’s security features. For this we need a final step:</p><p>Open <strong>System Preferences &gt; Security and Privacy &gt; Privacy &gt; Full Disk Access:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Wjf5VULfh5LyYVCIP73dLw.png" /></figure><p>Now, we need to add cron to the list.</p><p>For this, in your terminal:</p><pre>Ashwins-MacBook-Pro:sitemonitor myMac$ cd /usr<br>Ashwins-MacBook-Pro:sitemonitor myMac$ open .</pre><p>Then drag the sbin folder to the Favorite section. This is so when we go to add the cron to the full disk access, it will be easy to navigate to the item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*tlVSCNDf5xiCdX0yDR8dSw.png" /></figure><p>Now the cron job should be running fine.</p><p>This has been a learning experience for me. If you have any questions for me, do let me know in the comments section below. Thank you.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb843084c0a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/server-monitoring-and-sending-alert-to-them-team-when-its-down-using-python-script-cb843084c0a9">Is The Server Down? Send Automated Alerts to Your Team Using Python</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making your UI Elements to bounce with Bouncable Protocol]]></title>
            <link>https://ashwinshres.medium.com/making-your-ui-elements-to-bounce-with-bouncable-protocol-6d6c622eb63a?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6c622eb63a</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 03 May 2020 12:08:12 GMT</pubDate>
            <atom:updated>2020-05-03T12:14:46.164Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLmIN7P1Q2PpJ9aOzsG%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLmIN7P1Q2PpJ9aOzsG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="215" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f4b9625a6ea4bc33a6395830ac0ced1/href">https://medium.com/media/2f4b9625a6ea4bc33a6395830ac0ced1/href</a></iframe><p>In this article, we will be making a swift protocol which when conformed by any class which inherits UIView, can bounce by transform scale. We are not going to cover the whole bounce and fly animation in this post though. We will come back to making a view flyable later down the series with Flyable protocol. For this we are going to add CABasicAnimation, to the layer of the desired view, thus making it bounce.</p><p>This is Part 2, of a series <strong>Swift Protocols and adding those nifty functionalities in your app using them. </strong>The base article of the series can be found here : <a href="https://medium.com/@ashwinshres/swift-protocols-and-adding-those-nifty-functionalities-in-your-app-using-them-50a9680891ef">https://medium.com/@ashwinshres/swift-protocols-and-adding-those-nifty-functionalities-in-your-app-using-them-50a9680891ef</a></p><p>In the <a href="https://medium.com/@ashwinshres/making-your-ui-elements-to-shake-with-shakeable-protocol-ea6ac5dc8ffb">previous part of this series</a>: we have already gone through the basics of CALayer and CABasicAnimation , so we will jump directly to implemenation in this article.</p><p>Here, we are trying to scale any view by its root layer bounds. So what do we need to to that?</p><p>We need, an animation by the keypath of “transform.scale.xy”, the one we talked in previous article. We also need the initial and final scale of the transformation, the duration of animation, and the repeat count for the animation. In this, we will be adding animation completion handler too, to notify the caller that the animation was completed. From this, we can figure out the protocol defination, the blueprint of methods and properties we need to cally out this bounce functionality.</p><pre><strong>protocol</strong> Bouncable: UIView {<br>    <strong>func</strong> bounce(didBounce: <strong>@escaping</strong> () -&gt; ())<br>    <strong>var</strong> bounceScale: CGFloat { <strong>set</strong> <strong>get</strong> }<br>    <strong>var</strong> initialScale: CGFloat { <strong>set</strong> <strong>get</strong> }<br>    <strong>var</strong> bounceRepeatCount: Float { <strong>set</strong> <strong>get</strong> }<br>    <strong>var</strong> bounceDuration: Double { <strong>set</strong> <strong>get</strong> }<br>}</pre><p>That’s the blue print of our protocol.</p><p>Now coming to the core implementation, as I have already talked in the first part, about how we are going to demo a sample implementation by the end of this series by adding all type of protocols, we are going to add a default implementation of <strong>func</strong> bounce(didBounce: <strong>@escaping</strong> () -&gt; ()) as this same functionality will be shared by many classes adopting this protocol.</p><pre><strong>extension</strong> Bouncable {</pre><pre><strong>    func</strong> bounce(didBounce: <strong>@escaping</strong> () -&gt; ()) {<br>        CATransaction.begin()<br>        <strong>let</strong> scaleAnimation = CABasicAnimation(keyPath: &quot;transform.scale.xy&quot;)<br>        scaleAnimation.duration = bounceDuration<br>        scaleAnimation.repeatCount = bounceRepeatCount<br>        scaleAnimation.autoreverses = <strong>true<br>        </strong>scaleAnimation.fromValue = initialScale<br>        scaleAnimation.toValue = bounceScale<br>        CATransaction.setCompletionBlock {<br>            didBounce()<br>        }<br>        layer.add(scaleAnimation, forKey: &quot;scale&quot;)<br>        CATransaction.commit()<br>    }</pre><pre>}</pre><p>Here, we have used CATransaction</p><blockquote><strong>CATransaction</strong></blockquote><blockquote>A mechanism for grouping multiple layer-tree operations into atomic updates to the render tree.</blockquote><p>CATransaction is used here to get notified when animation completes, so we can notify back to caller with out handler.</p><pre><strong>class</strong> BounceAbleView: UIView, Bouncable {</pre><pre><strong>    var</strong> bounceDuration: Double = 2.0<br>    <strong>var</strong> bounceScale: CGFloat = 2.0<br>    <strong>var</strong> initialScale: CGFloat = 0.5<br>    <strong>var</strong> bounceRepeatCount: Float = 2</pre><pre>}</pre><pre><strong>class</strong> ProductViewController: UIViewController {</pre><pre><strong>    @IBOutlet</strong> <strong>var</strong> bouncableView: BouncAbleView!</pre><pre><strong>    override</strong> <strong>func</strong> viewDidLoad() {<br>        <br>        <strong>super</strong>.viewDidLoad()<br>        bouncableView.bounce {<br>            // do what you want to do after bounce completed<br>        }<br>    }</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*yE1R65ihe6Gwj4pbG9XbFw.png" /></figure><p>So, this is much the gist of the thing.</p><p>In the next article , we will be adding a Tapable functionality with protocol to a UIView or any class which inherits UIView .</p><p>If you have any questions or suggestions, feel free to post them in the comment section.</p><p>Thanks for reading.</p><p>Happy Coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6c622eb63a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making your UI Elements to Shake with Shakeable Protocol]]></title>
            <link>https://ashwinshres.medium.com/making-your-ui-elements-to-shake-with-shakeable-protocol-ea6ac5dc8ffb?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6ac5dc8ffb</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 03 May 2020 12:07:07 GMT</pubDate>
            <atom:updated>2020-05-03T12:08:42.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1rgYNeoFfZhhsEZ6Xa6Iw.jpeg" /></figure><p>In this article, we will be making a swift protocol which when conformed by any class which inherits UIView, can shake along X-axis or Y-axis. For this we are going to add CABasicAnimation, to the layer of the desired view, thus making it shake.</p><p>This is Part 1, of a series <strong>Swift Protocols and adding those nifty functionalities in your app using them. </strong>The base article of the series can be found here :</p><p><a href="https://medium.com/@ashwinshres/swift-protocols-and-adding-those-nifty-functionalities-in-your-app-using-them-50a9680891ef">https://medium.com/@ashwinshres/swift-protocols-and-adding-those-nifty-functionalities-in-your-app-using-them-50a9680891ef</a></p><p>Please go through it, before you start with this article.</p><h3>Starting with the core first:</h3><p>I won’t bore you with the basics of UIView as there is a plethora of very good articles and tutorials about it. However, would like to give a quick outline of CALayer.</p><p><strong>From Apple documentation:</strong></p><blockquote>A CALayer is an object that manages image-based content and allows you to perform animations on that content.</blockquote><p>Every UIView is just a wrapper around CALayer, it’s the root CALayer object of a view that is used to render the view It can be accessed by calling the layer property. While coding we often use:</p><pre><strong>open</strong> <strong>class</strong> <strong>func</strong> animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions = [], animations: <strong>@escaping</strong> () -&gt; Void, completion: ((Bool) -&gt; Void)? = <strong>nil</strong>)</pre><p>to animate a view property like: frame, backgroundColor, alpha, transform and constraints. But we can animate a view, by animating it’s CALayer as well. So What’s the difference between UIView animation and CALayer animation?</p><p>Animating a frame of a UIView can be a daunting task for CPU. Even if we add UIView animations, in the end, all animations are converted to Core Animation-style animations; that is, everything is animated using Core Animation. Here is a nice answer posted in Stack overflow on the same question: <a href="https://stackoverflow.com/a/38965402">https://stackoverflow.com/a/38965402</a></p><p><strong>From Apple documentation:</strong></p><blockquote><strong>Core Animation</strong> provides high frame rates and smooth animations without burdening the CPU and slowing down your app. Most of the work required to draw each frame of an animation is done for you. You configure animation parameters such as the start and end points, and Core Animation does the rest, handing off most of the work to dedicated graphics hardware, to accelerate rendering.</blockquote><p>Coming back to the topic of our article, here we are trying to shake a UIView along X-axis on certain conditions met, or when a user takes an action. To give it a case scenario, let’s suppose, we want to shake a UITextField along X-axis when a user enters invalid data. Shaking any UIView i.e. we are actually adding animation to its root layer, means we are trying to animate its position. Let’s set up our animation first:</p><pre><strong>let</strong> animation = CABasicAnimation(keyPath: &quot;position&quot;)</pre><p>Here in the above code sample, we have created a new CABasicAnimation with it’s keyPath “position”. CABasicAniamtion can have following items as its key path: position, opacity, backgroundColor, transform(transform.scale.x) . More on this can be found <a href="https://developer.apple.com/documentation/quartzcore/cabasicanimation#2776772"><strong>here</strong></a></p><p>From Apple’s documentation:</p><blockquote><strong>CABasicAnimation</strong></blockquote><blockquote>An object that provides basic, single-keyframe animation capabilities for a layer property.</blockquote><p>Next, is how long do we want to animate i.e. shake the textfield along xAxis in seconds</p><pre>animation.duration = 0.05</pre><p>How many times do we want to repeat the animation:</p><pre>animation.repeatCount = 5</pre><p>After changing the position, do we want to play the animation in reverse?</p><pre>animation.autoreverses = <strong>true</strong> // it&#39;s false by default</pre><p>Now we need to provide the start and end position of the animation:</p><pre>let distance: CGFloat = 5.0</pre><pre>animation.fromValue =  NSValue(cgPoint: CGPoint(x: center.x - distance, y: center.y))</pre><pre>animation.toValue =  NSValue(cgPoint: CGPoint(x: center.x + distance, y: center.y))</pre><p>Here, we have animated the position of the layer from the layer’s center.x minus a distance value of 5.0 to center.x adding a distance value of 5.0</p><p>And then added the animation to the layer:</p><pre>layer.add(animation, forKey: &quot;position&quot;)</pre><p>The full code snippet for above is:</p><pre><strong>func</strong> shakeAlongXAxis() {<br>    <strong>let</strong> animation = CABasicAnimation(keyPath: &quot;position&quot;)<br>    animation.duration = duration<br>    animation.repeatCount = repeatcount<br>    animation.autoreverses = <strong>true<br>    </strong>animation.fromValue =  NSValue(cgPoint: CGPoint(x: center.x - distance, y: center.y))<br>    animation.toValue =  NSValue(cgPoint: CGPoint(x: center.x + distance, y: center.y))<br>    layer.add(animation, forKey: &quot;position&quot;)<br>}</pre><p>Now let’s make a Protocol limiting adoption to UIView</p><pre>protocol ShakeableX where Self: UIView {<br>    var duration: Double {set get}<br>    var repeatcount: Float {set get}<br>    var distance: CGFloat {set get}<br>    func shakeAlongXAxis()<br>}</pre><pre>extension ShakeableX {<br>    <br>    var duration: Double {<br>        set { duration = newValue }<br>        get { return AnimatableConstants.shakeDuration }<br>    }</pre><pre>    var repeatcount: Float {<br>        set { repeatcount = newValue }<br>        get { return AnimatableConstants.shakeCount }<br>    }</pre><pre>    var distance: CGFloat {<br>        set { distance = newValue }<br>        get { return AnimatableConstants.shakeDistance }<br>    }</pre><pre>    func shakeAlongXAxis() {<br>        let animation = CABasicAnimation(keyPath: &quot;position&quot;)<br>        animation.duration = duration<br>        animation.repeatCount = repeatcount<br>        animation.autoreverses = true<br>        animation.fromValue =  NSValue(cgPoint: CGPoint(x:   center.x - distance, y: center.y))<br>        animation.toValue =  NSValue(cgPoint: CGPoint(x: center.x + distance, y: center.y))<br>        layer.add(animation, forKey: &quot;position&quot;)<br>    }</pre><pre>}</pre><p>Here we have ShakeableX protocol with default implementation provided in the extension as for any UIVIew or its subclasses like UIButton, UIImageView . The reason we added a default implementation rather than implementing the method in the class which conforms this protocol is because for all UIView and subclasses, the implementation would be same in our example.</p><p>Do go through this article : <a href="https://medium.com/@ashwinshres/protocol-and-limiting-protocol-adoption-f211d05e45d8">https://medium.com/@ashwinshres/protocol-and-limiting-protocol-adoption-f211d05e45d8</a>. for more info on this.</p><p>Also, we have made a struct with default value of our different constants / variables for the purpose of this article series.</p><pre><strong>struct</strong> AnimatableConstants {<br>    <strong>static</strong> <strong>let</strong> shakeCount: Float = 5<br>    <strong>static</strong> <strong>let</strong> shakeDuration: Double = 0.05<br>    <strong>static</strong> <strong>let</strong> shakeDistance: CGFloat = 5<br>}</pre><p>That’s all, now we can just conform this protocol to any UIView or it’s subclass and call shakeAlongXAxis() method to shake the view.</p><pre><strong>class</strong> AppTextField: UITextField, ShakeableX {</pre><pre><strong>    func</strong> shakeIfInputIsEmpty() {<br>        <strong>if</strong> (text ?? &quot;&quot;).isEmpty {<br>            shakeAlongXAxis()<br>        }<br>    }</pre><pre>}</pre><p>If we want to change the shakeCount, shakeDuration, shakeDistance, we can just provide those values here like:</p><pre><strong>class</strong> AppTextField: UITextField, ShakeableX {</pre><pre><strong>    var</strong> duration: Double = 0.5<br>    <strong>var</strong> distance: CGFloat = 10<br>    <strong>var</strong> repeatcount: Float = 10</pre><pre><strong>    func</strong> shakeIfInputIsEmpty() {<br>        <strong>if</strong> (text ?? &quot;&quot;).isEmpty {<br>            shakeAlongXAxis()<br>        }<br>    }</pre><pre>}</pre><p>So this is much the gist of how we can make a protocol and conform it to Shake things along x-axis. In the code below, we have made a Shakeable protocol, which is inherited by both ShakeableX and ShakeableY, to shake things along both or either X-axis or Y-axis</p><pre><strong>protocol</strong> Shakeable {<br>    <strong>var</strong> duration: Double { <strong>set</strong> <strong>get</strong> }<br>    <strong>var</strong> repeatcount: Float { <strong>set</strong> <strong>get</strong> }<br>    <strong>var</strong> distance: CGFloat { <strong>set</strong> <strong>get</strong> }<br>}</pre><pre><strong>protocol</strong> ShakeableX: UIView, Shakeable {<br>    <strong>func</strong> shakeAlongXAxis()<br>}</pre><pre><strong>extension</strong> ShakeableX {</pre><pre><strong>    func</strong> shakeAlongXAxis() {<br>        <strong>let</strong> animation = CABasicAnimation(keyPath: &quot;position&quot;)<br>        animation.duration = duration<br>        animation.repeatCount = repeatcount<br>        animation.autoreverses = <strong>true<br>        </strong>animation.fromValue =  NSValue(cgPoint: CGPoint(x: center.x - distance, y: center.y))<br>        animation.toValue =  NSValue(cgPoint: CGPoint(x: center.x + distance, y: center.y))<br>        layer.add(animation, forKey: &quot;position&quot;)<br>    }</pre><pre>}</pre><pre><strong>protocol</strong> ShakeableY: UIView, Shakeable {<br>    <strong>func</strong> shakeAlongYAxis()<br>}</pre><pre><strong>extension</strong> ShakeableY  {</pre><pre><strong>    func</strong> shakeAlongYAxis() {<br>        <strong>let</strong> animation = CABasicAnimation(keyPath: &quot;position&quot;)<br>        animation.duration = duration<br>        animation.repeatCount = repeatcount<br>        animation.autoreverses = <strong>true<br>        </strong>animation.fromValue =  NSValue(cgPoint: CGPoint(x: center.x, y: center.y - distance))<br>        animation.toValue =  NSValue(cgPoint: CGPoint(x: center.x, y: center.y + distance))<br>        layer.add(animation, forKey: &quot;position&quot;)<br>    }<br>}</pre><pre><strong>class</strong> AppTextField: UITextField, ShakeableX, ShakeableY {<br>    <strong>var</strong> duration: Double = 0.0<br>    <strong>var</strong> repeatcount: Float = 0.0<br>    <strong>var</strong> distance: CGFloat = 0.0</pre><pre><strong>    func</strong> shakeIfInputIEmpty() {<br>        <strong>if</strong> (text ?? &quot;&quot;).isEmpty {<br>            shakeAlongXAxis()<br>            shakeAlongYAxis()<br>        }<br>    }</pre><pre>}</pre><p>Note: when we add both shakeAlongXAxis() and shakeAlongYAxis() , the first one gets cancelled as we add a new CABasicAnimation on the layer. Adding both x-axis and y-axis shaking simultaneously requires a few code modification, which I am leaving for some other time 😀.</p><p>In the next article,</p><p><a href="https://medium.com/@ashwinshres/making-your-ui-elements-to-bounce-with-bouncable-protocol-6d6c622eb63a">https://medium.com/@ashwinshres/making-your-ui-elements-to-bounce-with-bouncable-protocol-6d6c622eb63a</a></p><p>we will be adding a <strong>Bouncable</strong> functionality with protocol to a UIView or any class which inherits UIView</p><p>If you have any questions or suggestions, feel free to post them in the comment section.</p><p>Thanks for reading.</p><p>Happy Coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6ac5dc8ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Protocols and adding those nifty functionalities in your app using them]]></title>
            <link>https://ashwinshres.medium.com/swift-protocols-and-adding-those-nifty-functionalities-in-your-app-using-them-50a9680891ef?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a9680891ef</guid>
            <category><![CDATA[features]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-protocol]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 03 May 2020 11:58:01 GMT</pubDate>
            <atom:updated>2020-05-03T15:09:54.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpJXCxagNrbys9aakHCeIw.jpeg" /></figure><p>If you are an ios developer, who might have come across and use knowingly or unknowingly protocols in swift, then this article series is for you, my friend. So brace yourself and enjoy this ride with me, as we are going to learn about protocols and also use them to make a few features for ourselves using them along the way.</p><p>For a sneak peek, here is a video demo of what we are about to build by the end of this series:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8S3XwQM0r8w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8S3XwQM0r8w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8S3XwQM0r8w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e26d202e6c763d954f6f469b63d8f329/href">https://medium.com/media/e26d202e6c763d954f6f469b63d8f329/href</a></iframe><p>The video above is just for demonstration purposes for now. Trust me it’s going to be a lot better.</p><p>In the above demo, a few key features if you have noticed are:</p><ol><li>Shakeable functionality, where the shoe image shakes when double tapped on the screen</li><li>Animated like functionality, on double tap on the screen -&gt; which then flies to the heart icon at the top right corner</li><li>Bounce effect on the heart icon at the top right corner, as the flying heart reaches the icon</li><li>Floating emojis at the bottom right corner, just like Facebook/Instagram live floating emojis</li><li>Rotating image with pan to rotate functionality</li><li>Shimmer effect on the heart icon at the top right corner</li><li>Pulsate animation to show a pulsating view just like tinder app</li></ol><p>These are a few functionalities or protocols which provide those functionalities, we are going to develop or may be more as we progress along the way in this series of articles.</p><p>But firstly addressing the elephant in the room <strong>Protocols.</strong></p><blockquote>A <em>protocol</em> defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be <em>adopted</em> by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to <em>conform</em> to that protocol.</blockquote><p>Source: <a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html"><strong>Apple Docs</strong></a></p><p>So basically in a simple language, we can say that protocol is something that gives us the power to do a task or add functionality.</p><h3>Protocol Syntax:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*bNLzZ-H8waMlwM_peINmYw.png" /></figure><p>Protocols are defined in a very similar way to classes, structures, and enumerations.</p><p>If you see the definition provided by Apple above, it’s written <em>“Any type that satisfies the requirements of a protocol is said to conform to that protocol.”</em>, so what does this mean ???</p><p>In our own way, looking at the video demo above, we can say, we have a protocol <strong>Shakeable, </strong>and anyone satisfies the need to shake, can conforms this protocol and shake about its x-axis or y-axis or both (we will come back to this later ind detail).</p><p>Similarly, suppose we want something to bounce in the screen.. what do we do? Maybe, we make a protocol <strong>Bouncable</strong>, such that anything which satisfies the need of this <strong>Bouncable</strong> protocol and conforms to this, can bounce on the screen.</p><h3>Talking about real implementation case scenario.</h3><p>Consider, you are making an e-commerce app, where on product display you need to show product image and shake it along x-axis on a certain actions performed by the user. What do we do?</p><p>Let’s make a class ProductImageView which inherits UIImageView.</p><pre><strong>class</strong> ProductImageView: UIImageView {</pre><pre>}</pre><p>And then add a method <strong><em>shakeAlongxAxis()</em></strong> with necessary implementation to shake the image view.</p><pre><strong>class</strong> ProductImageView: UIImageView {</pre><pre><strong>    func</strong> shakeAlongxAxis() {<br>         // necessary implementation here<br>    }</pre><pre>}</pre><p>But as you progress with your app, a new requirement comes your way, your client now asked you to add this shaking feature when someone types in an invalid email address in the login form and clicks the login button. What do you do??? Maybe you add the same method in your AppTextField class which inherits UITextField to give the functionality.</p><pre><strong>class</strong> AppTextField: UITextField {<br> <br>      <strong>func</strong> shakeAlongxAxis() {<br>           // necessary implementation here<br>      }</pre><pre>}</pre><p>And then, this same feature is needed somewhere else and on and on and on. You start thinking, maybe there is a better way to do this. That’s when the protocol comes handy. In the larger vision, you start considering a solution (protocol), which can provide us this feature of shaking something along x-axis if we just confirm our class to this protocol.</p><pre><strong>protocol</strong> ShakeAble {<br>     <strong>func</strong> shakeAlongXAxis()<br>}</pre><pre><strong>extension</strong> ShakeAble {</pre><pre><strong>    func</strong> shakeAlongXAxis() {<br>         // implementation here<br>    }</pre><pre>}</pre><pre><strong>class</strong> AppTextField: UITextField, ShakeAble {</pre><pre><strong>    override</strong> <strong>func</strong> draw(<strong>_</strong> rect: CGRect) {<br>        <strong>super</strong>.draw(rect)<br>        shakeAlongXAxis()<br>   }</pre><pre>}</pre><pre><strong>class</strong> ProductImageView: UIImageView, ShakeAble {</pre><pre><strong>    override</strong> <strong>func</strong> draw(<strong>_</strong> rect: CGRect) {<br>        <strong>super</strong>.draw(rect)<br>        shakeAlongXAxis()<br>    }</pre><pre>}</pre><p>Now both <strong><em>ProductImageView</em></strong> and <strong><em>AppTextField</em></strong> can conforms to <strong><em>ShakeAble </em></strong>protocol and shake along x-Axis.</p><p>Suppose, one day client comes in and then says, “I want the product image view to not just shake but bounce as well when someone taps on it”. We then just need to create a Bouncable protocol and add necessary bouncing code and conforms it to ProductImageView, for it to bounce.</p><pre><strong>protocol</strong> Bouncable {<br>    <strong>func</strong> bounce()<br>}</pre><pre><strong>extension</strong> Bouncable {</pre><pre><strong>    func</strong> bounce() {<br>        // implementation here<br>    }</pre><pre>}</pre><pre><strong>class</strong> ProductImageView: UIImageView, ShakeAble, Bouncable {</pre><pre><strong>    override</strong> <strong>func</strong> draw(<strong>_</strong> rect: CGRect) {<br>        <strong>super</strong>.draw(rect)<br>        shakeAlongXAxis()<br>        bounce()<br>    }</pre><pre>}</pre><p>This is the pretty much gist of the thing. Starting next article:</p><p><a href="https://medium.com/@ashwinshres/making-your-ui-elements-to-shake-with-shakeable-protocol-ea6ac5dc8ffb">https://medium.com/@ashwinshres/making-your-ui-elements-to-shake-with-shakeable-protocol-ea6ac5dc8ffb</a></p><p>we will be developing those features / protocols which we saw in the video demo using Protocol Oriented.</p><p>If you have any questions or suggestions, feel free to post them in the comment section. If you like the post, do clap and share it with your friends.</p><p>Thanks for reading.</p><p>Happy Coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a9680891ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualize Your iOS App’s Dependency Graph]]></title>
            <link>https://medium.com/better-programming/visualizing-dependency-graph-in-project-71210a5de269?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/71210a5de269</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 16:19:03 GMT</pubDate>
            <atom:updated>2020-05-06T13:07:00.865Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand the shape of your codebase</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuT7AYte_mD6uhTgs6E9ZQ.png" /></figure><p>In my previous <a href="https://medium.com/@ashwinshres/cleaning-up-the-resources-in-ios-project-1dad7e50bec1">article</a>, I wrote about how we can use the different tools available to remove unused resources, classes, functions, and localized strings . I hope you guys liked it.</p><p>In this article, I’m going to talk about another tool I usually use to get an in-depth analysis of my codebase. Here, we’re talking about the <em>dependency graph</em> in our project. So what’s a dependency graph?</p><blockquote>“In mathematical terms, a dependency graph is a <a href="https://en.wikipedia.org/wiki/Directed_graph">directed graph,</a> where directed edges connect the nodes and indicate a directional dependency.” — <a href="https://blog.ndepend.com/without-dependency-graph-flying-blind/">Eric Dietrich</a></blockquote><p>I’d like to talk more about the dependency graph, but maybe in a separate article next time. The tool I’m going to explain is one I’ve been using for some time to get an overview of the classes and structs in my project — how big they are, how they are linked with one another, and which classes are dependent on which. Let’s dive into the actual usage first and then come back to the explanation.</p><p>This tool is the <a href="https://github.com/PaulTaykalo/objc-dependency-visualizer">Objective-C And Swift Dependencies Visualizer</a> and uses .o(object) files to generate a dependency graph.</p><p>To use this tool: enter the following command in your terminal first:</p><pre>git clone <a href="https://github.com/PaulTaykalo/objc-dependency-visualizer.git">https://github.com/PaulTaykalo/objc-dependency-visualizer.git</a> ;<br>cd objc-dependency-visualizer ;</pre><p>Now go and build your iOS project in Xcode, and then enter the command:</p><pre>./generate-objc-dependencies-to-json.rb -w -s &quot;&quot; &gt; origin.js ;</pre><p>What this above command does is it takes your project from the derived data that you just built before entering the above command and then prepares a directed graph of your classes. Now enter:</p><pre>open index.html</pre><p>The above command opens your default browser and shows the chart.</p><p><strong>Note: </strong>This might not work in Safari, so do use Chrome or Firefox to open that index.html file.</p><p>For demo purposes, I’ve used my existing project to prepare the below chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuT7AYte_mD6uhTgs6E9ZQ.png" /></figure><p>I know it looks vague, but I had to zoom out to show all of the classes. A closer look at the graph is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bd_opavnjQi5P_ZQ8PaUw.png" /></figure><p>So all these orange circles are the view controllers, the brown ones are the constants and structs, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HL39ycccTmsOn7WGymZyA.png" /></figure><p>Clicking on one circle highlights it with all the other classes it’s dependent on or the ones that have a dependency on it, as shown in the above image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zopB7NyK6851_RuZNDZuBw.png" /></figure><p>If you closely view the dependency graph, you’ll notice there are some circles far apart from the main cluster — these are called <em>islands</em>. They’re separate bits of code that aren’t dependent on the main codebase and might/might not serve the purpose of the project.</p><p>Islands aren’t necessarily bad, but from the dependency graph view, we can see that we can surely delete the whole island, as it serves no purpose.</p><p>So the gist of all this is using the dependency-graph viewer, we can see the distribution of the codebase in our project. It gives an on-the-fly analysis of the codebase. It also helps us to see the <em>cyclic dependency</em> between the classes. A cyclic dependency is formed when two or more abstractions have direct or indirect dependencies to each other.</p><h3>Conclusion</h3><p>Thanks for reading. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71210a5de269" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/visualizing-dependency-graph-in-project-71210a5de269">Visualize Your iOS App’s Dependency Graph</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Clean Up the Resources in an iOS Project]]></title>
            <link>https://medium.com/better-programming/cleaning-up-the-resources-in-ios-project-1dad7e50bec1?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dad7e50bec1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 16:17:37 GMT</pubDate>
            <atom:updated>2020-05-06T12:26:20.760Z</atom:updated>
            <content:encoded><![CDATA[<h4>Run a Ruby script to clean up unused code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIPNr8TBkmHEh07mIFii2Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@zhenhappy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">pan xiaozhen</a> on <a href="https://unsplash.com/s/photos/cleaning?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Writing code is an iterative process. You write a certain functionality, and after certain months, the requirement may change and you have to remove it. And then another new feature is introduced which can be deemed unnecessary again. But that’s the life of a program: it needs to change as time changes and updates to meet the current requirement. But with the functionalities addition and removal over the time of development, often we end up with unused resources like classes, variables, methods, image assets and localized strings and even <a href="https://en.wikipedia.org/wiki/Dead_code"><strong>dead code</strong></a><strong>. </strong>This only increases our computation time and memory. This also makes our code hard to maintain. So it’s always good to clean your code and look for those cases once in a while.</p><p>Yes, we have to clean our code, and one year is a lot of time.</p><p>But it’s not as hard as it sounds. It’s not that we have to dive deep into every line of code and find those unused files and resources. There are some tools that help us to do that. Today, I am going to list down a few in this article that I use for this. If you use any other tools, do let me know in the comment section below, so I could also go and try out those.</p><p>First, let’s list the resources/files that we are going to talk about in this article.</p><ol><li>Unused swift functions and variables.</li><li>Unused localized strings.</li><li>Unused image resources.</li><li>Visualizing dependency graphs in the project.</li></ol><p>So let’s get started.</p><h3>Unused Swift Functions and Variables</h3><p>For this I use a Ruby script, which you can find <a href="https://github.com/PaulTaykalo/swift-scripts">here</a>. This script searches for unused swift functions, and variables at the specified path.</p><p>Go to the <a href="https://github.com/PaulTaykalo/swift-scripts">link</a> and clone the repository or download the <a href="https://github.com/PaulTaykalo/swift-scripts/blob/master/unused.rb">unused.rb</a> file, and place it in the root directory of your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Pt47pLFHneNaDxkKgh2qg.png" /></figure><p>For demo purposes, I have made this sample app Colors and added a method setUpCameraView() in <strong>ViewController.swift</strong> which has not been called from anywhere.</p><pre>import UIKit</pre><pre>class ViewController: UIViewController {<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>    }</pre><pre>    func setUpCameraView() {</pre><pre>    }</pre><pre>}</pre><p>Now open the terminal, navigate to the project directory, and enter the command.</p><pre>ruby unused.rb</pre><p>The output of the above is:</p><pre>Total items to be checked 6<br>Total unique items to be checked 6<br>Starting searching globally it can take a while<br>Item&lt; func setUpCameraView [] from: Colors/ViewController.swift:22:0&gt;<br>Item&lt; class AppDelegate [] from: Colors/AppDelegate.swift:12:0&gt;<br>Item&lt; var window [] from: Colors/AppDelegate.swift:14:0&gt;</pre><p>So, we see that setUpCameraView() is not called from anywhere in the app and is safe to remove.</p><p>Note: Had the method been a private method, it would not have shown in the result list. We should be careful about this, though.</p><p>If you want unused private methods also to be shown in the result, we need to update the <strong><em>unused.rb</em></strong> file. Just add <strong>private func </strong>in the list of line matches on line 11 of the file.</p><pre>if match = line.match(/(func|let|var|class|enum|struct|protocol|private func)\s+(\w+)/)</pre><p>In this way, we can list down all the unused functions, constants, variables, class, enum, struct, protocols in the project which has not been used anywhere.</p><p>You can integrate it to the Xcode as well with a <em>Custom Build Phase/Run Script,</em> the details are explained in the repo itself.</p><h3>Unused Localized String</h3><p>Another occurrence of unused things in the codebase after iterations are localized strings. We often end up with them, although they are not used anywhere in the project. To remove these, I use <a href="https://github.com/ijoshsmith/abandoned-strings"><strong><em>abandoned-strings</em></strong></a><em> by </em><a href="https://github.com/ijoshsmith">ijoshsmith</a>. This program will find the unused localized strings from all *.strings file in a given path.</p><p>The thing with this command-line program is that it’s still in swift 3, but <a href="https://github.com/blanksblanks"><strong><em>blanksblanks</em></strong></a><strong><em>,</em></strong><em> </em>has migrated it to swift 5 <a href="https://github.com/blanksblanks/abandoned-strings"><strong><em>here</em></strong></a>.</p><p>Steps to use this command-line program is as follows:</p><ol><li>Clone the <a href="https://github.com/blanksblanks/abandoned-strings"><strong><em>project</em></strong></a><strong><em> </em></strong>first and then run it.</li><li>An executable is generated in Products folder, navigate to the folder where the executable is generated by clicking “S<strong>how in Finder.</strong>”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGcG8NXfnq-R4OfiohkmdA.png" /></figure><p>3. Now open the terminal with this executable’s file path as terminal’s base path:</p><pre>Ashwins-MacBook-Pro:~ ashwin$ cd /Users/ashwin/Library/Developer/Xcode/DerivedData/AbandonedStrings-gnlgdvyltxanfeeyscyegpweluex/Build/Products/Debug</pre><pre>Ashwins-MacBook-Pro:Debug ashwin$</pre><p>4. After this, enter the command below to list all the unused localized strings in your project.</p><pre>Ashwins-MacBook-Pro:Debug ashwin$ ./AbandonedStrings /Users/ashwin/Desktop/Personal/Colors/Colors</pre><p>For demo purposes, I have added two localized strings, but I have not used it anywhere.</p><pre>&quot;ViewController_title&quot; = &quot;Hello&quot;;<br>&quot;ViewController_subtitle&quot; = &quot;Adios Amigo&quot;;</pre><p>Which gives us the result:</p><pre>Ashwins-MacBook-Pro:Debug ashwin$ ./AbandonedStrings /Users/ashwin/Desktop/Personal/Colors/Colors<br>Searching for abandoned resource strings…<br>Abandoned resource strings were detected:<br>/Users/ashwin/Desktop/Personal/Colors/Colors/Localizable.strings<br>ViewController_subtitle<br>ViewController_title</pre><pre>Ashwins-MacBook-Pro:Debug ashwin$</pre><p>So, in this way, we can list all the localized strings not used in the project and remove those.</p><p>Note: Make sure the subpath for analyzing is your project’s folder and it doesn’t include the Pods folder, because then it will try to find the unused localized strings in Pods as well, which we do not want.</p><h3>Unused Image Resources</h3><p>To list/remove unused image assets in my project, I use this powerful command line util called <a href="https://github.com/onevcat/FengNiao">FengNiao</a>. All you need to do is:</p><pre>&gt; git clone <a href="https://github.com/onevcat/FengNiao.git">https://github.com/onevcat/FengNiao.git</a><br>&gt; cd FengNiao<br>&gt; ./install.sh</pre><p>Note: You need Swift Package Manager (as well as Swift compiler) installed in your macOS.</p><p>Now, just navigate to your project folder and then enter the command:</p><pre>Ashwins-MacBook-Pro:Colors ashwin$ fengniao</pre><p>The output for my sample app that we have been using in this whole article, as we have not added images yet:</p><pre>Searching unused file. This may take a while...</pre><pre><strong>😎 Hu, you have no unused resources in path: /Users/ashwin/Desktop/Personal/Colors.</strong></pre><p>Now let’s add an image in Assets.xcassets and then hit the command again (but we are not using the image anywhere):</p><pre>Searching unused file. This may take a while...<br><strong>1 unused files are found. Total Size: 316.22 KB<br>What do you want to do with them? (l)ist|(d)elete|(i)gnore</strong></pre><p>You can → delete, list or ignore it.</p><p>When I wished to delete the result, the response I got:</p><pre><strong>What do you want to do with them? (l)ist|(d)elete|(i)gnore</strong> d<br><strong>Deleting unused files...⚙<br>1 unused files are deleted.<br>Now Deleting unused Reference in project.pbxproj...⚙<br>Unused Reference deleted successfully.</strong></pre><p>Or you can list them as well:</p><pre><strong>What do you want to do with them? (l)ist|(d)elete|(i)gnore</strong> l<br>316.22 KB /Users/ashwin/Desktop/Personal/Colors/Colors/Assets.xcassets/sampleImage.imageset<br><strong>1 unused files are found. Total Size: 316.22 KB</strong></pre><p>There are several options for the command, I encourage you to go and look at those in the repo’s <a href="https://github.com/onevcat/FengNiao/blob/master/README.md"><strong>README.md</strong></a><strong>. </strong>However, I would like to point out that, we can exclude the assets search in Pods and Carthage.</p><p>I have added<em> Visualizing Dependency Graph in the project </em>in the list, but I think the article is already long enough to explain Dependency Graph Visualization in the same article. To learn about Dependency Graph Visualization, check out <a href="https://medium.com/@ashwinshres/visualizing-dependency-graph-in-project-71210a5de269">this post</a>.</p><p>And if you have any questions or suggestions, feel free to post them in the comment section.</p><p>Also, if there are other libraries or Utils you use, please feel free to share them in the comment section below.</p><p>Thanks for reading.</p><p>Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dad7e50bec1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/cleaning-up-the-resources-in-ios-project-1dad7e50bec1">How to Clean Up the Resources in an iOS Project</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocol and limiting protocol adoption]]></title>
            <link>https://ashwinshres.medium.com/protocol-and-limiting-protocol-adoption-f211d05e45d8?source=rss-47ae0165ed2b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f211d05e45d8</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ashwin Shrestha]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 10:13:47 GMT</pubDate>
            <atom:updated>2020-05-03T15:13:50.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*atW35m1gFOA0y1E42D7BKQ.jpeg" /></figure><p>As I was just going through few Swift articles in medium, I came across this article titled <a href="https://medium.com/@abhimuralidharan/all-about-protocols-in-swift-11a72d6ea354"><strong>All about protocols in Swift</strong></a> by fellow Swift programmer, where he had explained about Swift protocol, a decent article if I might say.</p><p>There in the comment section, someone had asked a question about <strong>limiting protocol adoption</strong> as below:</p><blockquote>I have a question that is there any difference if I add constraint to the protocol itself, not to the protocol extensions?</blockquote><blockquote>protocol Attack where Self: Fighter {<br> func punch()<br>}</blockquote><blockquote>extension Attack {<br> func punch() { }<br>}</blockquote><p>I thought maybe I can elaborate/ answer more on that question as it was unanswered for a very long time. First of all, the questioner said, <em>“add constraint to the protocol itself”</em>, it’s not called adding constraint but <strong><em>“limiting protocol adoption”</em></strong>.</p><p>Coming back to the question, let me answer the question with a code snippet</p><pre><strong>protocol</strong> ShakeAble <strong>where</strong> Self: UIView {<br>    <strong>func</strong> shakeUIView()<br>}</pre><pre><strong>extension</strong> ShakeAble <strong>where</strong> Self: UIImageView {<br>    <br>    <strong>func</strong> shakeUIImageView() {<br>         print(&quot;Shaking uiiimageview in extension&quot;)<br>    }</pre><pre>}</pre><pre><strong>extension</strong> ShakeAble {<br>     <br>     <strong>func</strong> shakeAnyThing() {<br>          print(&quot;shaking anything which is subclass of UIView in extension&quot;)<br>     }</pre><pre>}</pre><p>Here in the above code snippet:</p><p>a. I have made a <strong>ShakeAble</strong> protocol with protocol adoption limited to <strong>UIView</strong> i.e. any class which inherits <strong>UIView</strong> or it’s subclasses like: <strong>UIButton</strong>, <strong>UIImageView</strong> etc can conform to this <strong>ShakeAble</strong> protocol and needs to implement the <strong><em>shakeUIView()</em></strong> method.</p><p>b. The protocol has been extended and has a method <strong><em>shakeUIImageView()</em></strong> with its default implementation, but this method can only be called by any class which is Subclass of <strong>UIImageView</strong> and conforms to <strong>ShakeAble</strong> protocol.</p><p>c. The protocol has another extension that has a method <strong><em>shakeAnyThing()</em></strong>, which can be called by any class which is Subclass of <strong>UIView (doesn’t need to be inherited from UIImageView) </strong>and conforms to <strong>ShakeAble</strong> protocol, but doesn’t necessarily implement the method.</p><pre><strong>class</strong> AppTextField: UITextField, ShakeAble {</pre><pre>      <strong>func</strong> shakeUIView() {<br>            print(&quot;shaking AppTextField&quot;)<br>      }</pre><pre>}</pre><p>Now as you can see, a class <strong>AppTextField</strong> which inherits from <strong>UITextField</strong> can conform to <strong>ShakeAble</strong> protocol, but it needs to implement the method <strong><em>shakeUIView()</em></strong> as there is no default implementation of it in any extension.</p><pre><strong>class</strong> ProductImageView: UIImageView, ShakeAble {</pre><pre><strong>      func</strong> shakeUIView() {<br>           print(&quot;shaking ProductImageView&quot;)<br>      }</pre><pre>}</pre><p>Similarly here we can see, a class <strong>ProductImageView</strong> which inherits from <strong>UIImageView</strong> can conform to <strong>ShakeAble</strong> protocol, as <strong>ProductImageView</strong> class inherits <strong>UIImageView</strong> which is a subclass of <strong>UIView</strong>. so, we need to implement the method <strong><em>shakeUIView()</em></strong>, but it may or may not implement the <strong><em>shakeUIImageView()</em></strong> method and just call the <strong><em>shakeUIImageView()</em></strong> method in protocol’s extension.</p><p>Let’s make another class <strong>MyView</strong> which inherits UIView and conforms to <strong>ShakeAble</strong> protocol:</p><pre><strong>class</strong> MyUIView: UIView, ShakeAble {</pre><pre><strong>      func</strong> shakeUIView() {<br>           print(&quot;called \(<strong>#function</strong>) at line: \(<strong>#line</strong>)&quot;)<br>      }</pre><pre>}</pre><p>So basically here, I conformed to <strong>ShakeAble</strong> protocol and added implementation for <strong><em>shakeUIView()</em></strong> method.</p><p>Now getting to the gist of this all blabber I have been doing here with some code examples:</p><ol><li><strong>Making an instance of MyUIView and calling the methods</strong></li></ol><pre><strong>let</strong> view = MyUIView(frame: .zero)<br>view.shakeUIView()<br>view.shakeUIImageView()<br>view.shakeAnyThing()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mskpbu6tSXPuFqUc2IWIDg.png" /></figure><p>What this above code snippet shows is, an instance of MyUIView can call, <strong><em>shakeUIView()</em></strong> and <strong><em>shakeAnything()</em></strong> methods but not <strong><em>shakeUIImageView(). </em></strong>This is because, though MyUIView has conformed to ShakeAble protocol, but the <strong>shakeUIImageView()</strong> in extension has explicitly limited protocol adoption for subclasses of <strong>UIImageView</strong>, though <strong>UIImageView</strong> is subclass of <strong>UIView. </strong><em>This is what limited protocol adoption is.</em></p><p><strong>2. Making an instance of AppTextField and calling the methods</strong></p><pre><strong>let</strong> view = AppTextField(frame: .zero)<br>view.shakeUIView()<br>view.shakeUIImageView()<br>view.shakeAnyThing()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZhD6hmKvYS2yKTfCElt3w.png" /></figure><p>The same is the case, which was pretty obvious. Now removing the method call, we try that again, and here is the result.</p><pre><strong>let</strong> view = AppTextField(frame: .zero)<br>view.shakeUIView()<br>view.shakeAnyThing()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MtTJPJ1yW9P-_7IBZfokw.png" /></figure><p>If you can see here “<strong>shaking anything which is subclass of UIView in extension</strong>” is the result of <strong><em>view.shakeAnyThing(), </em></strong>which is obvious as we are calling the default implementation fo the method from the extension. Now if we add this method in our own class <strong>AppTextField, </strong>the result is different.</p><pre><strong>class</strong> AppTextField: UITextField, ShakeAble {</pre><pre><strong>      func</strong> shakeUIView() {<br>           print(&quot;shaking AppTextField&quot;)<br>      }</pre><pre><strong>      func</strong> shakeAnyThing() {<br>           print(&quot;shaking anything which is subclass of UIView in AppTextField&quot;)<br>      }</pre><pre>}</pre><pre><strong>let</strong> view = AppTextField(frame: .zero)<br>view.shakeUIView()<br>view.shakeAnyThing()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*_qCCmf9lCFjuJxOakhdvMA.png" /></figure><p>This shows that the default implementation in extension can be overridden if implemented in the class.</p><p><strong>3. Now finally addressing the elephant in the room and our problem statement.</strong></p><pre><strong>let</strong> view = ProductImageView(frame: .zero)<br>view.shakeUIView()<br>view.shakeUIImageView()<br>view.shakeAnyThing()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upbhW3ni2sOYjD9v0CH3lQ.png" /></figure><p>So what we can see here is, if we limit the protocol adoption to the protocol, not extension, this works fine and any class which is a subclass of the one which we used for protocol adoption limitation can conform and implement the methods. <br>If we limit the protocol adoption in extension, anything can conform that protocol and implement the methods but the methods inside the extension which is limited to certain protocol adoption can not be called or overridden to implement, in our case:</p><pre><strong>protocol</strong> ShakeAble {<br>     <strong>func</strong> shakeUIView()<br>}</pre><pre><strong>extension</strong> ShakeAble <strong>where</strong> Self: UIImageView {</pre><pre><strong>      func</strong> shakeUIImageView() {<br>           print(&quot;Shaking uiiimageview in extension&quot;)<br>      }</pre><pre>}</pre><p>If our protocol had no limitation to protocol adoption, any instance of any type could conform to <strong>ShakeAble</strong> and implement <strong><em>shakeUIView()</em></strong> (per se), but the instance if it was of <strong>UIImageView</strong> type, only then it could call that <strong><em>shakeUIImageView()</em></strong> method.</p><p>If you have any questions or suggestions, feel free to post them in the comment section. If you like the post, do clap and share it with your friends.</p><p>Thanks for reading.</p><p>Happy Coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f211d05e45d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>