Lottie Animation in SwiftUI

Lottie is an open source animation file format that’s tiny, high quality, interactive, and can be manipulated at runtime. It has a the largest community of designers and developers. App like Duolingo and headspace are using lottie animation extensively. In this article, you will learn how to add animated view using Lottie in SwiftUI. You can find the animations in Lottie files and it can be exported to the JSON format. Just drag the downloaded json in your app. Lottie animation is rendered in real time. Lottie is open source library for iOS, Android and more. Step 1: Follow the installation guideline available here. You can install it using cocoapods. Step 2: Add your Lottie animation json file next to Info.plist. Step 3: Create a UIViewRepresentable for Lottie animation view. Step 4: We will pass animationName, loopMode and speed. Only animation name is mandatory so we will add a check if name is empty or not. By default speed is 1. Those are the available library provided loop mode – Step 5: Create an animated view inside the makeUIView function and play the animation. Constraints are added as well which will take the full width and height of the container.…

How to present WebView in SwiftUI?

SwiftUI does not provide any built in WebView. But you can easily create a WebView by the power of UIViewRepresentable. This code represents a stand alone View, so you can call it from any other View just like you would anything in SwiftUI. Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 You can also add some delegates to enhance your webview if needed. Planning to apply for an iOS job? Check out this article to uplift your resume! Also helpful – SwiftUI and Swift Interview preparation. Happy job hunting!

Share sheet in SwiftUI using UIActivityViewController

There is no built in share sheet in SwiftUI but you can easily implement a share sheet using UIActivityViewController. UIActivityViewController is a simplified built in interface to share contents such as texts, images and URLs. You can also define custom actions as well using UIActivityViewController. Let’s create an UIViewControllerRepresentable for UIActivityViewController and pass some text to share. The ShareSheetView will look like – Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 Full code Planning to apply for an iOS job? Check out this article to uplift your resume! Also helpful – SwiftUI and Swift Interview preparation. Happy job hunting!

How to show local notification always at the same time?

For local notifications, you need to generate the notification content and provide a time or location. Both Local and remote notifications inform the user to do specific action by displaying a notification badge/alert with/without sound. The badge generally shows when the app is on background or not running state. The local notification remind user that he has some relevant things to do in the app. As notification is disruptive and it hurts user’s attention, you must ask for permission to show them. The permission part is really simple and it is same as all the other type of permission in iOS – Let’s create notification content – Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 Now create a trigger with a specific time. Here, the notification will be launched at the same(8.00AM) time daily. Finally add the notification in the UNUserNotificationCenter to launch.

How to show local notification when the app is foreground?

In order to display the notification when the app is foreground/open, you need to add a delegate method. You have to implement UNUserNotificationCenterDelegate in order to get the local notification when the app is open. Add the following extension in AppDelegate Add don’t forget to add this in application’s didFinishLaunchingWithOptions function. Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 If you are using SwiftUI’s new app cycle “SwiftUI App” then the following code can help you.

How to implement a glassmorphic card in SwiftUI?

Glassmorphism is a popular design trend which provides stunning UI and UX for the user. You can find glassmorphic UI everywhere in apple’s design. The most common way to achieve glassmorphic UI is by adding blur to the background, adding inner shadow, drop shadow as well as highlighting the border. After adding the blur effect whatever is behind the background is beautifully “morphed” into the element itself. Glassmorphic UI item really shines while using vividly coloured background. A glassmorphic card is a design pattern that involves creating a transparent card with a reflection effect, similar to the look of a sheet of glass. To implement a glassmorphic card in SwiftUI, you can use the Card view provided by the SwiftUI framework and customize its appearance with the background(_:) and cornerRadius(_:) modifiers. Here’s an example of how to create a glassmorphic card in SwiftUI: In this example, the GlassmorphicCard view is a generic view that takes a Content parameter and displays it within a Card view. The background(_:) modifier is used to set the background color of the card to clear, which makes the card transparent. The cornerRadius(_:) modifier is used to round the corners of the card, and the shadow(color:radius:x:y:)…

Swift iOS interview questions and answers – Part 5 – Architectural & Design pattern

Part 5 consists Swift iOS interview questions and answers of design and architectural pattern. In this article, I will cover the different concepts of design and architectural pattern briefly such as MVC, MVVM, VIP, VIPER, structural, behavioural and creational design pattern in iOS etc. What is MVC and explain the main concern of MVC? MVC/Model-View-Controller is an architectural pattern used to decouple user-interface (view), data (model), and application logic (controller). The main concern of MVC is that it does not enforce developers to decouple responsibilities. For example: network related codes are often found in ViewController. ViewController is treated as dumping station for all kind of logics sometimes. For this reason, MVC is often called massive view controller. MVC roles are described here – • Model will only encapsulates the data, it must not contain any business logic.• View will encapsulate what user can see in the UI and it also should not have business logic.• Controller should maintain all kinds of business logic that goes between the View and the Model. Explain OOP in the context of an iOS developer Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. In the…

How to implement custom font in SwiftUI?

Fonts can influence our emotions. They can also impact the user experience. In SwiftUi, It is very easy to use custom font by the help of info.plist and the font modifier. In this article, I will demonstrate how to add a font in the project. Where to download the font: There are a lot of custom font available on internet. Before using any downloaded font just check the font copy-write and think about the user experience of that font. You can download font from Google font, fontsquirrel, fontspace, DaFont etc. Add the font Download your desired font(Ex: Roboto-light.ttf from Google font) Add the font file in the project. Check copy items if needed, create groups and add to targets. Go to the Info.plist file and click the + icon. Add Fonts provided by application Unfold Fonts provided by application and click the + icon. Write the font name(Roboto-light.ttf) in the value section of item 0. You can use your custom font by the .custom font modifier. The name must be the same as the font name.

Swift iOS interview questions and answers – Part 4 – Memory management

In this article, I have answered the questions related to one of the main concepts of Swift iOS interview which is memory management. I will cover some core concepts of memory management such as ARC, retain cycle, circular dependency, reference cycle, capture list, and capture of self, etc. Memory management is an important aspect of software development and is crucial for building performant and reliable applications in iOS. As a result, it’s often a topic covered in both senior and junior iOS developer interviews. For junior developers, memory management questions can help to assess their understanding of basic programming concepts and their ability to write efficient and stable code. Junior developers may be asked questions about reference counting, ARC, strong and weak references, and how to avoid strong reference cycles. For senior developers, memory management questions can help to assess their experience and expertise in writing performant and scalable applications. Senior developers may be asked questions about performance optimization techniques, such as profiling and heap analysis, and how to handle more advanced memory management challenges, such as managing memory in large and complex applications. In both cases, questions about memory management can help to identify the candidate’s ability to write…

Swift iOS interview questions and answers – Part 3 – Threading & concurrency

Part 3 consists Swift iOS interview questions and answers of thread and concurrency. It will cover concurrency-related topics such as GCD, NSOperation, operation queue, lock, semaphore etc. Threading and concurrency are important concepts in software development and are especially relevant in mobile development, where limited processing power and battery life are major concerns. For this reason, they are often included in technical interviews for senior iOS developers. In iOS development, understanding threading and concurrency is crucial for building responsive and efficient applications. An iOS developer should be familiar with the various tools and techniques available for managing concurrent tasks, such as Grand Central Dispatch (GCD) and Operation Queues, and know how to use them to optimize the performance and responsiveness of an application. The ability to understand and address race conditions, deadlocks, and other synchronization issues is an important skill for a senior iOS developer. This includes understanding the use of locks, semaphores, and other synchronization mechanisms, as well as the implications of multithreaded programming on the overall architecture and design of an application. Asking about threading and concurrency in an interview for an iOS developer position is meant to assess the candidate’s ability to create performant and scalable applications…

What is Copy On Write(COW) in Swift?

Copy-On-Write (COW) is a memory management technique used in Swift programming language to optimize the performance of memory allocation and deallocation operations. In COW, whenever a new instance of a data structure is created, the original data structure is not modified, instead, a new copy of the data structure is created in memory and modifications are made to the new copy. Copy-on-write is a highly used strategy in Swift for optimising memory usage. The main idea of COW is that when multiple callers want to access the resources which are same, you can put them pointing to the same resource. The state of the resource will be maintained until a caller tries to modify its “copy” of the resource. The main advantage is that if a caller never makes any modifications, no true copy need ever be created. Don’t confuse copy on right with reference type. This technique helps to reduce the time and memory overhead involved in creating and managing multiple copies of large data structures. Benefits of using COW in Swift include: COW is a powerful technique for optimizing the performance and memory usage of Swift applications, and helps to ensure that data structures are manipulated safely and…

Xcode Cheat Sheet – Most used shortcuts and tips

If you’re an iOS developer, it’s essential to have a thorough understanding of the tools you use on a daily basis. After all, you likely spend 40 or more hours a week working with them, so knowing small hacks that can help increase your productivity can make a big difference. I wanted to share some of my most used shortcuts and tips to help you get the most out of it. Xcode is a powerful integrated development environment (IDE) used for creating applications for Apple’s various platforms. It’s packed with features and tools that can help streamline your workflow and improve your efficiency. Subscribe to my Newsletter and get the high-quality printable version of the poster as a WELCOME GIFT. Or consider to to support my work! PDF, Image Take a look at SwiftUI specific Xcode cheat sheet Xcode SwiftUI Efficiency Hack One of my favorite shortcuts is the “Build and Run” command, which is activated by pressing “Command + R”. This command will build your project and run it in the simulator or on a connected device, saving you time and effort. Another one is “Command + Shift + O” which allows you to quickly search for a file…

ARC & when to use strong, weak, unowned

Memory management is one of the important concept when it comes to mobile application development. Memory leaks and app crashes are very common due to poorly managed memory in iOS apps. In this short article, I will describe ARC and the use of strong, weak and unowned. ARC/Automatic Reference Counting Swift uses Automatic Reference Counting for maintaining memory footprint. It figures out when the objects should be deallocated based on retain count. Each object increases the retain count when it is allocated strong reference is assigned to that object. An object’s retain count is decreased by 1 when a strong reference is removed from that object. When the total retain count reaches 0 the object is deallocated from the memory by ARC. Strong Swift uses a strong reference by default. If you create a variable, constant or property for a reference type, it is strong type by default unless you declare it as weak or unowned. This is also true for passing references into functions or closures. Strong references in Swift increment the retain count each time it is allocated. When you are using strong reference you need to consider checking retain cycle and memory leaks.A retain cycle will happen…

Swift iOS interview questions and answers – Part 2 – Auto layout & UIKit

Part 2 consists Swift iOS interview questions and answers of UI – Auto layout & UIKit. It will cover UI related topics such as frame, bound, autolayout constraints, xib, storyborad, safe area etc. What is bounding box? The bounding box is the smallest rectangle completely enclosing all points in the path, including control points for Bézier and quadratic curves. What is CGpath? An immutable graphics path: a mathematical description of shapes or lines to be drawn in a graphics context. Do your need weak or unowned for UIView animation? weak or unowned self is used to prevent retain cycles. After UIView animation runs, the memory is deallocated even if it is strongly referenced. Weak and unowned is not needed for animation code block. You don’t need to use [weak self] in static function UIView.animate() You need to use weak when retain cycle is possible and animations block is not retained by self. The external object reference captured by them will only be kept for certain amount of time, which means it’s definitive that it’s going to be executed at one point of time. After this, it will be released so there is no chance of reference cycle which leads to memory leak. What is…

Why should you use private outlets by default?

Access control is very powerful concept in object oriented programming language. Access control helps prevent you from using objects in ways they were not intended to be used. Access control lets you carefully control what properties and methods an entity exposes. The reason is to build higher levels of abstraction. A programmer should never need to look at the private details of a class, module or function. They should be able to read the public interface and its documentation and just use it. We all agree that access control is important but when comes to outlets we are using default protection level. We have a tendency to overlook outlet’s access control as Xcode generates them. The default access or protection lever is internal access. Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. When you create an outlet by doing control + drag from the interface to the related source file, default access level outlet will be created by XCode. I have started using private outlets, not for a long. There are a couple of benefits of using private outlets which seem very convincing to…

Swift iOS Interview Questions and Answers – Part 1 – Language Features

Welcome to the first part of our series on Swift iOS interview questions and answers! In this blog post, we will focus on language features, and cover some common questions you may be asked about Swift during an iOS interview. As a junior iOS developer, mastering the language features of Swift is crucial to your success in this field. This is why “Swift IOS Interview Questions and Answers – Language Features” is a vital resource for anyone looking to develop their skills and grow their career in iOS development. Interview questions on Swift language features are often used by hiring managers to assess a candidate’s level of expertise and understanding of the language. Junior iOS developers must be well-versed in these questions and answers in order to perform well during job interviews. By having a good understanding of the language, you can demonstrate your ability to write efficient and reliable code, which is essential in the iOS development field. However, knowing the language features of Swift helps junior iOS developers to mid-level iOS developers write better code. Understanding the syntax and structure of the language will allow you to write cleaner and more readable code, making it easier for others…

Swift iOS interview questions and answers

Swift is a very powerful language and it combines both object-oriented and functional programming. It has many exciting features such as closures, function pointers, tuples, and multiple return values, generics, functional programming patterns, etc. In this article, I have collected the most asked Swift iOS interview questions and provided the simplest answers possible. As an iOS developer, it’s essential to have a strong understanding of the core concepts that underlie the platform. Whether you’re interviewing for a new job or just looking to brush up on your skills, these five areas are sure to come up in any iOS-related conversation: language features, UI, threading and concurrency, memory management, and architecture and design patterns. In this blog post, we’ll take a closer look at each of these concepts and provide some example questions to help you prepare for your next iOS interview. I have arranged the questions by five major concepts. In future, I will add difficulty level(Beginner, Intermediate and Advanced) (Worth reading Acing iOS Interview with Confidence) Part – 1 Language features Swift is the primary programming language used for iOS development, and it’s important to understand its syntax, semantics, and features. The questions are related to Swift language features…

How to detect multiple gestures simultaneously?

If you want to detect multiple gestures at the same time, you can use SwiftUI’s simultaneously function. You can simply say that it is opposite of sequenced gestures described in How to implement sequential gestures using sequenced? For example, this code triggers multiple gestures simultaneously

How to implement sequential gestures using sequenced?

If you want to collaborate multiple gestures and make them detectable one after another, you can use SwiftUI’s sequenced modifier. To implement combined gestures or sequential gestures you need to create multiple gestures. In this case, the second gesture can be detected only after the first gesture is completed. As an example, the following code creates a circle with two gestures. After long pressing the circle, you can drag it and the gesture recognisers will be detected one after another.

How to implement tap and multiple tap gestures in SwiftUI?

SwiftUI provides gesture modifier to implement tap gesture on a view. Multiple gesture can be achieved though adding count numbers. To try it out let’s create a view and add a tap gesture recogniser To detect multiple taps, we need to pass number of taps in count parameter

How to pop or dismiss view programmatically in SwiftUI?

To pop or dismiss the view programmatically in SwiftUI, you can use use @Environment(\.presentationMode) as a variable and call wrappedValue.dismiss(). In the DetailView we have called wrappedValue.dismiss() wen the button is tapped. You can also get the same outcome if you bind a visibility property in the DetailView instead of @Environment(\.presentationMode)

How to show a detail view from list item in SwiftUI?

You can use NavigationLink in the List modifier to show the detail view or a new view when user taps on the list item. For example, we could create a simple DetailView which will be shown when list item is tapped. The main ContentView has list of chocolates and when user taps on the item it shows detail view with item name and the random amount of sugar.

How to present detail view using NavigationLink in SwiftUI?

NavigationLink helps you to present new view or detail view from the navigation view. While using NavigationLink it pushes the a details view on the navigation stack with built in animation. To demonstrate this, the following code creates a DetailView which will be presented from NavigationView.

How to show date picker in SwiftUI?

SwiftUI date picker is a very handy built-in modifier(DatePicker) for selecting a specific date, time, or both. A date picker has four modes: date, time, date and time, count down timer. You can display date picker in contact, wheels and inline style. You can present the date picker in the following way: If you want to show the whole calendar to pick the date you can use .datePickerStyle(GraphicalDatePickerStyle()) You can also play with different types of range while using the date picker. The most commonly used range is …Date() where you can select any date until the present date or Date()… to select the date from the present date.

How to show picker in SwiftUI?

SwiftUI’s dedicated picker can display one or more scrollable items from which you can choose your desired item. It is recommended to use pull-down menu instead of a picker if the list is not very long. A picker typically appears at the bottom of the screen or in a popover. When you choose something in the picker, you can see an automatic checkmark next to the selected item. To try it out let’s create a simple picker with tasty treats:

How to show a menu in SwiftUI?

SwiftUI menu is a versatile control for presenting a menu of actions. It supports submenus and the primary action from iOS 15. SwiftUI menu is more user friendly and advance than the action sheet. Let’s try a menu named “Manage Document” and a submenu called “Upload”. Both menus have two options. Custom primary action help you to write action when you press the item on the menu.

How to show a context menu in SwiftUI?

The context menu provides you access to additional functionality related to onscreen items without cluttering the screen. You can create a context menu using .contextMenu modifier. The context menu is triggered with a long press. Each menu item in the context menu represents a SwiftUI button. You can add action, text and icon on those buttons. Here, we have a context menu with three buttons. You can use the “Long press for menu” to reveal a context menu. When open, a context menu displays a preview of the item and lists the commands that act on it. It is recommended to place the most frequently used menu items at the top of the menu.

How to show an action sheet in SwiftUI?

From iOS 15 you can present an action sheet using confirmationDialog() modifier. In SwiftUI, the action sheet shows a confirmation dialogue using data to produce the dialogue’s content and a localized string key for the title. You need to provide a title text, a state variable for toggle action sheet visibility and a couple of other views like buttons. Inside the confirmationDialog() buttons you can use .cancel or .destructive to provide SwiftUI specific look and feel.

How to create background blur in SwiftUI?

Glassmorphism is a very trending UI design paradigm nowadays. We can use the semi-transparent blurry background to give more focus on the foreground content. SwiftUI provides .blur() modifier to create the background blur but it has very limited functionality compared to UIVisualEffectView. Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 SwiftUI does not provide any built-in visual effects view or something related to background blur. But we can use UIKit in SwiftUI using UIViewRepresentable. To implement a background blur effect in SwiftUI, I am using the Apple-provided VisualEffectBlur.swift file(Fruta) in the article. UIVisualEffectView can support multiple styles from ultra-thin to thick. .systemUltraThinMaterial.systemThinMaterial.systemMaterial.systemThickMaterial.systemChromeMaterial You can simply pass the style using VisualEffectBlur(blurStyle: .systemThinMaterial). The default blur style is .systemMaterial. VisualEffectBlur.swift

How to create horizontal or vertical ScrollView in SwiftUI?

ScrollView in SwiftUI presents its content within the scrollable region. ScrollView can scroll horizontally, vertically, or both. The alignment of the ScrollView is vertical. If you want to make it horizontal then you need to use the horizontal parameter for the ScrollView. In the following example, the ScrollView allows the user to scroll through multiple RoundedRectangle child views. You can use showsIndicators false/true to toggle the scroll indicator. Output

How to use ZStack to put views on top of other views in SwiftUI?

If you want to place a view on top of another view(s), you need to use ZStack. The ZStack places each child view a higher z-axis value than the one before it. It simply means that later children are presented “on top” of the earlier child views. The very common use of Zstack is placing a test on top of a view. Let’s place a text on top of a view – The default ZStack alignment is center. ZStack doesn’t have a spacing property but you can offset() to move the position of child view. Output

Built-in shapes in SwiftUI

Shapes in SwiftUI are a very innovative, exceptionally simple way to build a user interface component. In this article, we will take a look at simple shapes like rectangle, rounded rectangle, ellipse, circle and capsule. The common use of built-in shapes is clipping content, creating custom views, custom component etc. Using the built-in shapes, I will create a cell at the end of this article. Rectangle It creates a box with specified dimensions. Rounded rectangle It provides a rectangular shape with rounded corners. We can simply create a rounded rectangle from the rectangle. It is aligned inside the frame of the view containing it. Mostly used in cell and overlay. Circle Use Circle to circular shape. The circle’s radius equals half the length of the frame rectangle’s smallest edge. Mostly used for clipping the avatar. Capsule A capsule is an enhanced version of a rounded rectangle where the corner radius is half the length of the rectangle’s smallest edge. Normally used to create a badge or a button. Ellipse The Ellipse is a distorted version of a circle. An ellipse aligned inside the frame of the view containing it. Output I have used Rectangle to create an orange background. Other…

How to show an alert in SwiftUI?

iOS 15 makes the alert presentation a piece of cake. You can show an alert using the alert() modifier. Buttons inside the alert will dismiss the alert view when it is tapped. You can create multiple buttons inside an alert. If you don’t have any .cancel button, it will be added automatically at the end. You can also create .destructive button as the alert view button is a regular SwiftUI button. Multiple buttons with the role:

Use of #file, #line, #function when debugging

#file, #line and #function are very common to debug features that are available in other languages like C++. I found it very useful to implement debug/logging manager. We can get the current file name, line number and function name from the #file, #line and #function respectively.

Use of custom view modifier for reusability in SwiftUI

Custom view modifier is very powerful concept in SwiftUI which will allow you to write reusable code. If you are using same kind of modifiers throughout multiple of views, it is better to create a custom view modifier. The main benefit of custom view modifier is that it will help you to generate a good design system. Creating custom view modifiers promotes consistency, clarity, and quality in the SwiftUI application design process. It can also deliver significant competitive advantages for small team. Conform the ViewModifier protocol when you want to create a reusable view modifier that you can apply to any view. In this example, you can notice that both buttons have the same set of modifiers(the only font difference is font) and it makes sense to reuse those modifiers. The example below combines several modifiers to create a new modifier called CustomButtonModifier. As you can see that I have passed font as a parameter for CustomButtonModifier to differentiate primary and secondary button. You can apply the custom view modifier using modifier(_:) keyword but I prefer to create a function using the name of the custom modifier inside the View extension. It makes the code more readable. Output

What is given-when-then testing in Swift?

Given-When-Then (GWT) is a structured way to write unit tests. I find it is particularly useful when I need to write complex unit tests. The structure helps me to write and understand unit test faster than the traditional approach. Using this concept, we break down and write a unit test into three sections. Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 Let’s think about a real world test case scenario. Test case: Add food to a food cart. As a user, I want to add a food item to my food cart and the total food items are increased. Given: The food cart is initially empty. Total food item = 0When: Add three food items in the cartThen: User should have three food items in cart. The Given-When-Then was proposed by Dan North as part of behaviour-driven development. Benefits of having GWT approach in iOS project Given-When-Then (GWT) testing in Swift (and in general)…

Show alert in Swift – Simplify using protocol

Alert as UIAlertController is used in almost every iOS application. It is one of the most basic components of the application. We can simplify the UIAlertController using protocol. In this short article, I have created AlertDisplaying protocol to resolve alert related code duplication. Alert can contain a title, a message, style(alert or action sheet), one or multiple actions(alert buttons) and an alert text field. Alert protocol – AlertDisplaying Now add the default implementation of AlertDisplaying protocol We can simply use it by conforming the AlertDisplaying protocol

What does the associated type mean in Swift 5+?

The associated type in Swift gives a placeholder name to a type that will be used as part of the protocol. When the protocol is conformed, the actual type to use for that it is specified. The associated type makes the protocol generic by providing a type placeholder. I was very confused about the associated type at the beginning. I found that the best way to understand this concept is to use code example. For instance, I have created a protocol for the shopping cart. In the shopping cart, I can add, remove or count different type of shopping items. The type of shopping items will depend on which type of store I have created. Now, I have created two structs. The first one is the Food struct which will be used for the associated type. The second one is FoodStore which will conform to our ShoppingCartable protocol. Here, the Swift compiler uses Food type to fill the placeholder in the associated type. However, Food is a very simple type but we can also use a type alias in case of complicated types.

Grasp mutating function in Swift under three minutes!

The understanding of the mutating function depends on the understanding of reference and value types. In Swift, The properties of value types cannot be changed within its instance methods by default. You need to use a mutating keyword in the instance method to change the properties of a value type. The mutating function has the power to mutate the values of the properties. The reference type (for example class) will share a single instance of the object and pass the same reference to a function The value type (for example struct) will make a copy of it and passes only the value. You can also read Value and reference types in Swift -A deep dive for better understanding. Why does a struct need mutation? You need to use the mutating function if you will change any state contained within the struct. Calling a mutating function returns a new struct in place as Struct is immutable. It works the same as passing an inout parameter to a function. The mutating keyword lets callers know that the method is going to make the value change. Calling a mutating functions on constants is not possible(e.g. let person = Person()). Because that would be…

How to use defer in Swift?

Using defer keyword in Swift code is uncommon. But, It is a very powerful concept for certain use case. The code block inside defer statement is executed just before transferring program control. It does not matter how program control is transferred. I find this concept particularly useful when I need to clean up something inside the function or perform an action that needs to happen even if an error is thrown. Another very common use case is closing the file after a certain operation in FileHandle. No matter how you exit, the defer statement is executed at the end. We can exit the current scope (The scope can be for in loop, do try-catch block, function body etc.) using single return, multiple returns or break. Here, the defer is executed in every possible case while exiting the scope. Writing the same exit code multiple times is not a smart thing to do. Multiple defer statements execution order If multiple defer statements appear in the same scope, the order they appear is the reverse of the order they’re executed.

How to use inout parameters?

All function parameters in Swift are constants by default. That means you can not change the value of the parameters. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. If you want a function to modify a parameter’s value then the parameter should be used as an inout parameter. The inout parameters can be updated inside the function. The updated value replaces the original value outside the function. There are some key restrictions that we want to remember when using inout parameters. You can’t use a constant(let) as the argument because constants can’t be changed. We can not set default values as inout parameters. The variadic parameters can’t be marked as inout as well. When you pass inout parameters as an argument you need to use an ampersand (&) directly before a variable. It will state that the function will modify the parameters. Planning to apply for an iOS job? Check out this article to uplift your resume! Also helpful – SwiftUI and Swift Interview preparation. Happy job hunting!

How to use DispatchGroup in Swift?

DispatchGroup allows you to add a set of tasks and schedule them for asynchronous execution. This behaviour can be helpful when progress can’t be made until all of the specified tasks are complete. For instance, If you have several long-running tasks to perform and you’d like to run some further logic, you need DispatchGroup. However, You can run each task sequentially, but it is not very efficient. In the code example, I have downloaded many images concurrently, followed by the makeCollage function. When all the images are downloaded, notify will be called. Get ahead of the competition and ace your next iOS interview with expert-curated resources. Check out the collection of SwiftUI and Swift interview questions and answers, behavioral interview tips, and the popular custom layout contents. Plus, go through the new section for Engineering Manager to help you excel in your career! Join my free Newsletter 🚀 Each call to enter() must be matched later on with a call to leave(), after which the group will call the closure provided to notify(). If you do not want to wait for the groups to finish, but instead want to run a function once all the tasks have completed, use the notify function…

Optional methods in protocols

In Swift, If you conform to a protocol you need to implement all its methods or properties. Optional methods are not allowed when implementing protocols. For instance: We can try some tricks to make the optional methods. Use default implementation using the extension. Splitting the protocols with many protocols and conform only necessary one. You can use typealias(How and when to use typealias in Swift?) to merge protocols. Using the @objc attribute on a Swift protocol. It provides the opportunity to mark methods as being optional. In this case, you can not use structs, enums and protocol extensions with that protocol.

How and when to use typealias in Swift?

The typealias is a simple but powerful concept in Swift. Type alias does not create new types. They simply provide a new name to an existing type. It makes long, compound types easy to manage. In Swift, we are passing the function to another function as an argument very often. In this case, We should use type aliasing to make it more readable. However, when it comes to working with compound types you would definitely notice the benefits of type aliasing. In this short article, I will show some common use of type aliasing. Type alias is declared using typealias name = existing type KEY TAKEWAY Use typealias in closures. Avoid using it in custom dictionary or the type that is more understandable without aliasing. Use of typealias in closure Think about an API call which will return String or error as a response. Here, you can notice the first section of code has a lot of parentheses. It looks complicated and ugly. Also, for implementing similar functions, it is not that logical to keep copy-paste the parameters. Using typealias make the signIn function easy to understand. In combine protocols Combining multiple protocol helps to understand code with less effort. We can create…

First-class functions in Swift

First-class functions are the core feature of a functional programming language. Swift isn’t a functional programming language. But, it has the power of first-class functions. In this short article let’s have a look at the first-class functions and their application. What can we achieve through first-class functions? Functions are first-class citizens in Swift. Grasping this powerful concept will make developer life easier. Swift first-class functions have the following abilities – You can store functions in constants and variables. You can pass a function or functions as arguments to other functions. One can also return functions from other functions. Storing functions in variables We can store a function in a variable or constant. For instance, create a property named feed. The feed property has a function type that is optional. This type does not accept any arguments and returns nothing. The entertain() function uses feed property references to do the specific feed action. Passing the functions as arguments Above all, Passing functions as arguments are using all most everywhere in Swift. SwiftUI is mostly based on this concept. You can read Map, FlatMap, Filter, Reduce – High order functions in Swift 5.4 to understand passing function as an argument and the use…

Map, FlatMap, Filter, Reduce – High order functions in Swift

Higher-order functions are used a lot in functional programming. A higher-order function is a function that takes one or more functions as arguments and returns a function or a value as its result. All other functions are first-order functions. Higher-order functions use closures to allow us to pass in functionality that can then determine how we want the method to sort, map, flatMap, filter and reduce in Swift collection types such as Array, set or Dictionary. To be more precise, Swift returns the results of an operation as a transformed array while using higher-order functions, on the other hand, a “pure functional language” will return a collection of functions. Higher-order functions provide a useful abstraction for things like callbacks and function chaining. One of the big advantages of using higher-order functions is the composition by adding multiple higher-order functions together. This technique reduces bugs and makes the code easier to read and understand. One can generate smaller functions that only take care of a specific portion e of logic by adapting higher-order functions. One can also compose more complex functions by using different smaller functions. Let’s create a higher order function in oder to understand the basics – Here, the first two functions are…

Use of final keyword in method and class

The Final is a class modifier that prevents it from being inherited or being overridden. While writing an API developer might have a class in the framework that can be abused or misused when subclassed. The solution will be the “final” keyword in this case which prevents class to be subclassed. You can also use final to methods, properties, and even subscripts of non-final classes. This will have the same effect, but for a particular part of the class. For class declaration by default, I am using the final keyword. When we use final keyword declaration, it does not need to be overridden which has better performance because final disables dynamic dispatch at runtime(saves runtime overhead). KEY TAKEWAYS Final is used to prevent a class from being subclassed or a method from being overridden.

How to use Variadic Parameters in Swift 5+?

A variadic parameter accepts zero or more values of a specified type. When creating API it seems more developer-friendly as we don’t needs to generate an array at the caller site in order to pass multiple arguments. The variadic parameter using three dots can be passed a varying number of input values when the function is called. KEY TAKEWAYS The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type. Recently released Swift 5.4 brings support for multiple variadic parameters. However, you can not use variadic parameters as inout parameters.

When to use computed properties over methods?

I prefer to use computed properties when I need to compose new data from existing data sources or I want to reduce a complicated, nested property name to a more readable and easy to use one (but update it when the original property changes). If the property body contains complex logic or is not following O(1), then I move to methods. Properties are tempting to use. They are often seen as lightweight values which makes it a risk if it contains heavy operations. We should use these properties to display data relative to existing data. Readability and smooth understanding of the code are key to make the decision. KEY TAKEWAYS You can use computed properties inside extensions. It performs its operations every time it’s called which can easily result in a performance decrease in costly operation. Computed properties won’t take any arguments.