<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Swift Anytime</title>
    <description>The latest articles on DEV Community by Swift Anytime (@swiftanytime).</description>
    <link>https://dev.to/swiftanytime</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1003423%2F3dff7a22-9754-4123-b392-e5de49fe09bd.jpg</url>
      <title>DEV Community: Swift Anytime</title>
      <link>https://dev.to/swiftanytime</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/swiftanytime"/>
    <language>en</language>
    <item>
      <title>Functions in Swift</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Thu, 23 Feb 2023 13:57:44 +0000</pubDate>
      <link>https://dev.to/swiftanytime/functions-in-swift-3e2c</link>
      <guid>https://dev.to/swiftanytime/functions-in-swift-3e2c</guid>
      <description>&lt;p&gt;The function is a set of commands/statements. To create a simple function, you first have to define and name it; generally, naming is according to the task you want it to perform. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var age = 18
let name = "Krishna"
print("Hi, I am " + "\(name)")
print("I am " + "\(age)")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The set of commands you see above may be needed more than once for the XYZ project, and programmers make work easy for people, including them. To use the same code every time, the concept of function is essential.&lt;/p&gt;

&lt;p&gt;Also, functions are like your school notes. You write down the notes given by your instructor, but when referring to it, you look through the problems and do not entirely solve them again. So functions reference your code every time you need them; initialize it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Declaring and Calling Functions
&lt;/h2&gt;

&lt;p&gt;Declaring a function and writing the code inside parenthesis will work precisely. The exciting thing is that you don't have to write many lines of code again now and then in the future. Call the function as shown in the example below, and it will perform it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func myInfo() {

  var age = 18
  let name = "Krishna"
  var line = ("Hi, I am " + "\(name) \n") + ("I am " + "\(age)")
  print(line)

}

myInfo()

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

&lt;/div&gt;



&lt;p&gt;If you see, it now looks better and structured. Just like "var" and "let" keywords, we have a "func" keyword for declaring a function. Then name the function like how&lt;br&gt;
you call your variables and constants but add open and close braces and end up with open and close parenthesis.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func car() {
    /* lines of code */
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function will never run automatically. To run a function, you need to call it whenever you wish to run it. Calling a function is simple, write "car()" and then whatever code is inside this function, the console will try running that.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Parameters
&lt;/h2&gt;

&lt;p&gt;You learned how to write a function and call it. But what if you want the other name instead of "Joey" or "Chandler" or "Xyz" every time?&lt;br&gt;
The answer is to use parameters in a function. The parameters help get new values every time you try calling a function.&lt;/p&gt;

&lt;p&gt;You can see a parameter "product" with a type String in the example below. Just like you assign a new value to a variable, you give a value to your function, which eventually helps replace that value everywhere you use that parameter in the code written inside the parenthesis of a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func appleProduct(product: String) {
//               ----------------- 
//                       ∣
//                  (Parameter)

  print("\(product)" + " is an Apple product")

}

appleProduct(product: "iPhone 13")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Example 2 with two Parameters

func tesla(model: String, year: Int) {
//        ------------------------- 
//                   ∣
//               (Parameter)

  print("Tesla" + " \(model)" + " was released in the year" + " \(year)")

}

tesla(model: "Roadster", year: 2018)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Return Values
&lt;/h2&gt;

&lt;p&gt;"Return" in programming means returning a value. The function receives the value from what you entered, but it can also return the value by giving it back to you.&lt;/p&gt;

&lt;p&gt;For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func circleArea(radius: Double) -&amp;gt; Double {

    let pi = 3.14
    var formula = pi*radius*radius

    return formula

}

let answer = circleArea(radius: 3.5)
print(answer)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: Return is similar to the print statement, but they are not the same. When you return a value and then call a function, it won't print any value. You must declare a variable or a constant and then print it with its help!&lt;/p&gt;

&lt;p&gt;So to return a value, add "-&amp;gt;" after the parameters list and when returning a value, write the keyword "return" just before your closing bracket of a function.&lt;/p&gt;

&lt;h2&gt;
  
  
  Argument Labels
&lt;/h2&gt;

&lt;p&gt;Until now, you only understood the overview concept of parameters, but when you name a parameter, it serves/assigns the same label to the argument, and the parameter name itself is known as "argument labels" and "parameter names".&lt;/p&gt;

&lt;p&gt;By default, the parameters use their parameter names as their argument labels.&lt;/p&gt;

&lt;p&gt;In simple terms, think like the x variable when you were in high school and solving some algebraic problems. When the coefficient of x is 1, you don't write 1x but x. During the time, you ignored writing 1 before your variable because it wasn't needed; just like that, with simple parameters in use in your function, you don't have to bother much about argument labels.&lt;br&gt;
Though you write a coefficient before the variable when it is greater than the value 1 because you can't just make it an assumption because it would make it intricate/complex to understand the problem, about the same, argument labels make your program readable and ease for you and other team members.&lt;/p&gt;

&lt;p&gt;Now your question could be:&lt;br&gt;
What's the position of the argument label in a function syntax?&lt;/p&gt;

&lt;p&gt;To simply answer it, the argument labels are just written before the parameter names and leave a space in between.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func marvel(year: Int, spiderman movie: String) {
//                     --------- -----
//                         |       |
//              (Argument Label) (Parameter Name)

    print("\(movie) was released in \(year)")

}

marvel(year: 2021, spiderman: "Spider-Man: No Way Home")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, you must have noticed that when you call the function marvel, you will write an argument label inside the round braces for the second parameter and not a parameter name, but that's the opposite when using it in a print statement.&lt;/p&gt;

&lt;p&gt;Another important thing you must have guessed is that the first parameter of this function will be used as a parameter name and argument label.&lt;/p&gt;

&lt;h2&gt;
  
  
  Excluding Argument Labels
&lt;/h2&gt;

&lt;p&gt;You can drop giving the name to an argument label by replacing it with a "_" (underscore). For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func marvel(_ year: Int, spiderman movie: String) {

    print("\(movie) was released in \(year)")

}
marvel(2021, spiderman: "No Way Home")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you use an argument label in your parameter, be careful to label it.&lt;/p&gt;

&lt;p&gt;Default Parameter Values&lt;br&gt;
Try remembering how you assigned a value to a variable at a time of declaring,&lt;/p&gt;

&lt;p&gt;var x = 3&lt;br&gt;
Declaring/assigning a value to a parameter is precisely the same.&lt;/p&gt;

&lt;p&gt;It would help if you kept in mind placing a default value parameter after the parameter without the default value. This is helpful, excluding the use of parameter with default value while calling the function.&lt;/p&gt;

&lt;p&gt;For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func demoFunction(x : Int, y : Int = 5) {
  print("Parameter without Default Value = \(x)")
  print("Parameter with Default Value = \(y)")
}

demoFunction(x: 3)
demoFunction(x: 3, y: 8) 
//like variables you can change the default value of a parameter to a new one
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What's next?&lt;/p&gt;

&lt;p&gt;Congratulations! You deserve to celebrate this moment. You have completed understanding, implementing, and learning one of the crucial topics of programming and, of course, Swift. We encourage you to read Arrays next; till then, have a great time ahead.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Optionals and Unwrapping in Swift</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Wed, 22 Feb 2023 13:44:36 +0000</pubDate>
      <link>https://dev.to/swiftanytime/optionals-and-unwrapping-in-swift-4nif</link>
      <guid>https://dev.to/swiftanytime/optionals-and-unwrapping-in-swift-4nif</guid>
      <description>&lt;p&gt;An Optional is a type of its own that can handle the absence of a value. Optionals can contain nil values and there are multiple ways to unwrap them. In this article, we will understand why not to unwrap them forcefully and how to unwrap them safely.&lt;/p&gt;

&lt;h2&gt;
  
  
  Optionals
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;A type that represents either a wrapped value or nil, the absence of a value.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Some examples of optionals are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Optional types either contain a value or nil. It can be defined as Optional&amp;lt;type&amp;gt;.
type? like Int? is syntatical sugar for Optional&amp;lt;type&amp;gt; like Int. */
struct Food {
var id: Int
var name: Optional&amp;lt;String&amp;gt; 
var description: String?
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Forced Unwrapping Optionals
&lt;/h2&gt;

&lt;p&gt;Forced unwrapping extracts the value of the optional variable. Forced unwrapping assumes the value is definitely not-nil. Thus, it throws a fatal error if the variable is nil.&lt;/p&gt;

&lt;p&gt;Optionals can be forced unwrapped by placing ! after the variable name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var name: String? = "Pasta"
var desc: String? = nil
print(name!) //Prints Pasta
print(desc!) //Leads to runtime error since desc is set to nil
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implicitly Unwrapped Optionals
&lt;/h2&gt;

&lt;p&gt;Implicitly unwrapped optionals are similar to optionals since they’re allowed to have nil value but they do not need to be checked before accessing. It’s called implicitly unwrapped since Swift force unwraps it every time. The drawback of this is same as forced unwrapping - if the value is nil when accessing, it leads to a fatal error.&lt;/p&gt;

&lt;p&gt;Similar to optionals, optional binding and optional chaining can also be used for implicitly unwrapped optionals.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Defining an implicitly unwrapped optional
var name: String!
//It will lead to runtime error if the value is nil when accessing
print(name) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Implicitly unwrapped optionals are mainly used for convenience when the value once initialised is never nil. Apple uses it for outlets. One has to be careful when using them since it is unsafe and can lead to runtime error if not handled carefully.&lt;/p&gt;

&lt;h2&gt;
  
  
  Optional Binding
&lt;/h2&gt;

&lt;p&gt;To safely unwrap the value of an Optional , use one of the optional binding control structures, including if let and guard let. Optional binding conditionally binds the wrapped value of an Optional instance to a new variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var name: String?
if let name = name {
    //Perform actions on the variable name
}
guard let name = name else {
    //Handle case where name name is nil
}
//Perform actions on the variable name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What is the difference between guard let and if let?
&lt;/h2&gt;

&lt;p&gt;guard let is designed to exit the current function, loop, or scope if the check fails so any values you unwrap using it will stay around after the check. Early exit from scope implies that the else block generally requires return or aborting the program.&lt;/p&gt;

&lt;p&gt;On the other hand, values unwrapped using if let are accessible in the if block only. It doesn’t require a return statement.&lt;/p&gt;

&lt;h2&gt;
  
  
  Optional Chaining
&lt;/h2&gt;

&lt;p&gt;Optional chaining is a method for querying and calling properties, methods or subscripts on an optional. If the value of the optional is nil, it fails gracefully. Optional chaining is specified by placing ? after the optional.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Consider the example of struct food defined above
 struct Meal {
    var food: Food?
    var calories: Int?
}
lunch = Meal()
if let foodID = lunch.food?.id {
    ...
} else {
    ...
}
//Values can also be set using optional chaining
lunch.food?.name = "Pizza"
//Optional chaining can be on multiple levels
struct Day {
    var breakfast: Meal?
    var lunch: Meal?
    var dinner: Meal?
}
var today = Day()
if let dinnerName = today.dinner?.food?.name {
    print(dinnerName)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;Optionals are a powerful type in Swift allowing us to initialise variables with nil. Optionals can be unwrapped forcefully by using force unwrapping (unsafe). Implicitly unwrapped optionals use force unwrapping to access variable each time which may also lead to runtime error if its nil.&lt;/p&gt;

&lt;p&gt;Optional binding is a safe way to unwrap an optional. Optional chaining gracefully accesses properties, methods and subscripts on an optional. Optional binding and chaining are suggested to use for utmost safety.&lt;/p&gt;

&lt;p&gt;Wrapping up the article, you learned about the core topics of Optionals related to interview questions. You are now equipped with all knowledge required to ace the interview regarding these kind of questions. Till then,&lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Sets in Swift</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Thu, 16 Feb 2023 14:07:07 +0000</pubDate>
      <link>https://dev.to/swiftanytime/sets-in-swift-48c2</link>
      <guid>https://dev.to/swiftanytime/sets-in-swift-48c2</guid>
      <description>&lt;p&gt;You may have come across the concept of Arrays and Dictionaries, two primitive types of collecting and storing the values, but there is a third one in the group called Sets.&lt;/p&gt;

&lt;p&gt;These three types are together referred to as Collection Types.&lt;/p&gt;

&lt;p&gt;If you're unfamiliar with Arrays and Dictionaries, we strongly suggest reading up on those concepts before continuing with this one.&lt;/p&gt;

&lt;h2&gt;
  
  
  What makes Sets different from Arrays/Dictionaries?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What are Sets?
&lt;/h3&gt;

&lt;p&gt;Sets are unsorted collections that contain unique values.&lt;br&gt;
Let’s understand with an example. So, for the first one we are declaring and initiating  collection of artists with unique values and then adding the name of an Artist using an .append() which already exists in the collection we created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var artists = ["Taylor Swift", "Arijit Singh", "Selena Gomez", "Badshah", "Drake"]

print(artists)
print(artists.count) // will print 5

artists.append("Badshah")
print(artists)
print(artists.count) // will print 6, even though two values are same
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, you'll note that the values are kept in a collection of type Arrays, which are kept as ordered collections and exhibit basic behavior (i.e., they keep an item in memory at a certain index). So, neither the array's original values nor the new one that was appended or added are compared in any way.&lt;/p&gt;

&lt;p&gt;Let's see what gets printed if we use the type Set, we will be creating a set out of this array to do so we'll open the parenthesis, input the variable's name (in this case, artists), and then close the parentheses. Last but not least, print it as usual, and if you're curious about how many items are included in your collection, you may use the .count method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(Set(artists))
print(Set(artists).count)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, you will notice that the output differs from what Array type delivered.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why use Sets?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Sets works with the different approach. They don't use indexes, so each time you access the collection, you'll get a new set of results—basically works like a random  generator and omits the same values you store in the collection. Given that you can't really mess up a Set and that its results inspire a certain degree of trust, developers turn to them often for storing unique data.&lt;/p&gt;

&lt;p&gt;Also remember that .append() doesn’t work with Sets but instead .insert(). The only reason is append means adding a value after the last one and Set doesn’t have a sorted method for storing values and hence you have to insert a value.&lt;/p&gt;

&lt;h1&gt;
  
  
  Creating Sets
&lt;/h1&gt;

&lt;p&gt;Values are still contained between square brackets, as they are with Arrays and Dictionaries, but the syntax is somewhat different. Whether you want to start with an empty set or a pre-populated one, there are various ways to do it.&lt;/p&gt;

&lt;h1&gt;
  
  
  1. Empty Set
&lt;/h1&gt;

&lt;p&gt;Well, this will be your method if you think on adding the values later to your program/project.&lt;/p&gt;

&lt;p&gt;It’s simple - Set()&lt;/p&gt;

&lt;p&gt;Just like how we convert an Array to Set, we follow a similar syntax but here we specify what Data Type the collection will hold, which goes inside angle brackets “” and followed by parenthesis “()” since it’s an empty collection.&lt;/p&gt;

&lt;p&gt;For your reference:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var species = Set&amp;lt;String&amp;gt;()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Set with an Array Literal
&lt;/h2&gt;

&lt;p&gt;With arrays, you must have seen that we can’t leave the square brackets empty without giving it’s type. Even when storing values, it’s a good practice to give the type to avoid further confusion in your program.&lt;/p&gt;

&lt;p&gt;Other syntax of an empty set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var cricketers: Set&amp;lt;String&amp;gt; = []
print(cricketers) // output contains no values
cricketers = ["Virat Kohli", "Hardik Pandya", "Rohit Sharma", "Arshdeep Singh", "KL Rahul"]
print(cricketers) // print the values added above
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Set with values initialized:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var species: Set&amp;lt;String&amp;gt; = ["Acinonyx jubatus", "Panthera leo", "Panthera pardus", "Panthera tigris"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here if you see, in both the cases we go back to how Arrays are initialized but with a mention of Set and it’s collection Data Type. Now, always remember to provide a type, otherwise Xcode or Playgrounds will pop an error&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Type 'Any' cannot conform to 'Hashable”&lt;br&gt;
for an empty set/array.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  3. Few other ways
&lt;/h2&gt;

&lt;p&gt;Swift is so intelligent that when you save a first value in a variable or a constant, it will automatically detect or assign a Data Type to it. This is a great feature for junior developers and especially newbies just getting started in the world of programming. However, you must specify that the data structure being used is a Set; otherwise, the data structure will be treated as an Array. There are two ways of telling:&lt;/p&gt;

&lt;p&gt;The first one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var movies: Set = ["Avatar", "Avatar 2", "Dil Dhadakne Do", "Gully Boy"]

print(movies) // The same syntax when specifying the Data Type at the time of declaration of the variable but mentioning as Set.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember, as discussed above, you can’t store this as an empty set.&lt;/p&gt;

&lt;p&gt;The second one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var books = Set(["Think Like a Monk", "Do Epic Shit", "The Psychology of Money", "Steve Jobs by Walter Isaacson", "Do Epic Shit"])

print(books) // will omit the same values
print(books.count) // will print 4

// The same syntax you saw at the start of this article when printing an Array collection as a Set
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that we purposely added “Do Epic Shit” for your better understanding that Sets will automatically omit the same value in the collection, making it a unique collection. But, you again have to be careful when adding values as “do epic shit” or “Do Epic shit” wouldn’t be counted as identical, and give the output of 5 values  instead.&lt;/p&gt;

&lt;p&gt;Congratulations! You should now have a solid grasp of the three major Collection Types in Swift: &lt;a href="https://www.swiftanytime.com/blog/arrays-in-swift/" rel="noopener noreferrer"&gt;Arrays&lt;/a&gt;, &lt;a href="https://www.swiftanytime.com/blog/dictionaries-in-swift/" rel="noopener noreferrer"&gt;Dictionaries&lt;/a&gt;, and Sets, thanks to the fundamental notion you learnt today.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understand UIResponder &amp; Responder Chain to Handle Events</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Wed, 15 Feb 2023 13:18:26 +0000</pubDate>
      <link>https://dev.to/swiftanytime/understand-uiresponder-responder-chain-to-handle-events-3aob</link>
      <guid>https://dev.to/swiftanytime/understand-uiresponder-responder-chain-to-handle-events-3aob</guid>
      <description>&lt;p&gt;In this article, you will learn how to handle events that communicate through the app.&lt;/p&gt;

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

&lt;p&gt;This is an abstract interface for responding to and handling events. An abstract interface is just combination of properties and methods to override them only. You can say, all the instances of UIResponder (responder objects) are the backbone of iOS apps. Here are some responder objects that are most commonly used:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;UIView&lt;/li&gt;
&lt;li&gt;UIViewController&lt;/li&gt;
&lt;li&gt;UIControl&lt;/li&gt;
&lt;li&gt;UIApplication&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note: You will learn about these components later in further articles.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How UIKit handle the events?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once an event occurs, UIKit dispatches them to the app's responder objects for handling. UIKit manages most responder-related behavior automatically, including how events are delivered from one responder to the next.&lt;/p&gt;

&lt;p&gt;There are several kinds of events, including touch events, motion events, remote-control events, and press events. To handle a specific type of event, a responder must override the corresponding methods. For example, to handle touch events, a responder implements the touchesBegan(), touchesMoved(), touchesEnded(), and touchesCancelled() methods. In the case of touches, the responder uses the event information provided by UIKit to track changes to those touches and to update the app's interface appropriately.&lt;/p&gt;

&lt;p&gt;In addition to handling events, UIKit responders also manage the forwarding of unhandled events to other parts of your app. If a given responder does not handle an event, it forwards that event to the next event in the responder chain. UIKit manages the responder chain dynamically, using predefined rules to determine which object should be next to receive an event. For example, a view forwards events to its superview, and the root view of a hierarchy forwards events to its view controller.&lt;/p&gt;

&lt;h1&gt;
  
  
  Relation between UIResponder, UIEvent and UIControl
&lt;/h1&gt;

&lt;p&gt;You know that responder objects can handle and respond to events (touch, motion, press).&lt;br&gt;
An UIEvent represents a single UIKit event that contains a type (it may be touch, press, motion, etc). When an event has been detected in the system, UIKit internally creates a UIEvent instance and dispatch it to the system to perform. All events are sent in the queue by calling UIApplication.shared.sendEvent() method.&lt;/p&gt;

&lt;p&gt;When an event comes to be performed from the queue, UIKit finds out the first UIResponder which is capable of handling the event, and sends it to the selected one.&lt;/p&gt;

&lt;p&gt;You can also handle system events manually by creating the UIResponder's subclasses by overriding the specific methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// All UIResponder classes which are using the custom touch events should override these methods.
open func touchesBegan(_ touches: Set&amp;lt;UITouch&amp;gt;, with event: UIEvent?)
open func touchesMoved(_ touches: Set&amp;lt;UITouch&amp;gt;, with event: UIEvent?)
open func touchesEnded(_ touches: Set&amp;lt;UITouch&amp;gt;, with event: UIEvent?)
open func touchesCancelled(_ touches: Set&amp;lt;UITouch&amp;gt;, with event: UIEvent?)


// All UIResponder classes which are using the custom press events should override these methods.
open func pressesBegan(_ presses: Set&amp;lt;UIPress&amp;gt;, with event: UIPressesEvent?)
open func pressesChanged(_ presses: Set&amp;lt;UIPress&amp;gt;, with event: UIPressesEvent?)
open func pressesEnded(_ presses: Set&amp;lt;UIPress&amp;gt;, with event: UIPressesEvent?)
open func pressesCancelled(_ presses: Set&amp;lt;UIPress&amp;gt;, with event: UIPressesEvent?)


// All UIResponder classes which are using custom motion like shake needs to override these methods.
open func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?)
open func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?)
open func motionCancelled(_ motion: UIEvent.EventSubtype, with event: UIEvent?)
open func remoteControlReceived(with event: UIEvent?)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, you know that UIEvents can be subclassed and sendEvent() can be manually called. Because you can not create custom event types (custom events may be problematic as they can be handled incorrectly by an unintended responder). Besides system events, UIResponders can also respond to "actions" in the form of Selectors - which is exactly performed using UIButton class which can dispatch actions after being touched.&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let customButton = UIButton(type: .custom) // or .system
customButton.addTarget(targetView, action: #selector(method_name), for: .touchUpInside)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is a problem i.e. UIResponders can fully detect touch events and they are not easy to handle. So you will check which touch event has been occurred?&lt;/p&gt;

&lt;p&gt;That's where UIControl (subclass of UIView) abstracts the process of handling touch events and provides the ability to assign actions to specific touch events.&lt;/p&gt;

&lt;h1&gt;
  
  
  Responder Chain
&lt;/h1&gt;

&lt;p&gt;In iOS, Responder Chain is the name given to an UIKit-generated linked list of UIResponder objects.&lt;/p&gt;

&lt;p&gt;The responder chain is responsible to handle all the events (like touch and motion) in iOS apps. If any responder can't handle a specific action or event, the event is sent to the next responder of the list to handle it until the list ends.&lt;/p&gt;

&lt;h1&gt;
  
  
  What next?
&lt;/h1&gt;

&lt;p&gt;In this article, we explained how UIResponder works in the iOS apps and handles events. Now, let's dive into some basic UIKit components to learn the basics of them. &lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to access private members of a class in Swift</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Tue, 14 Feb 2023 14:20:17 +0000</pubDate>
      <link>https://dev.to/swiftanytime/how-to-access-private-members-of-a-class-in-swift-2ng7</link>
      <guid>https://dev.to/swiftanytime/how-to-access-private-members-of-a-class-in-swift-2ng7</guid>
      <description>&lt;p&gt;This article will show you how to access a class's private members, such as variables and methods in Swift.&lt;/p&gt;

&lt;p&gt;In the normal case, you cannot access private members outside the scope of a class directly, but let's see what are the alternative ways to access members within and outside the scope of a class.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is the Private Access Control?
&lt;/h1&gt;

&lt;p&gt;In Swift, private is an access control used to define how types, functions, and other declarations can be accessed in your project. You can set the private accessibility (visibility) of classes, structs, enums, functions, variables, and so on.&lt;/p&gt;

&lt;p&gt;It restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is there any other access controls in Swift?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Swift provides a variety of access controls that can be used for different purposes. These are open, public, internal, file-private and private.&lt;/p&gt;

&lt;p&gt;In this guide, you will learn about private access control. Let's start.&lt;/p&gt;

&lt;h2&gt;
  
  
  Syntax of Private Access Control?
&lt;/h2&gt;

&lt;p&gt;Following is the syntax to declare a private variable or function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Declare a private variable/constant
private &amp;lt;variableType&amp;gt; &amp;lt;variableName&amp;gt; = &amp;lt;initialValue&amp;gt;

// Declare a private function
private func functionName() { 
    // function body
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand the above syntax:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;First, you can see how to declare a private variable or constant using private keyword.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then, you can see how to declare a private function.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  How to access private members?
&lt;/h1&gt;

&lt;h1&gt;
  
  
  1. Using public methods
&lt;/h1&gt;

&lt;p&gt;In Swift, you can access private properties using the public method by returning their values. Let's understand this by the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Decalring a class called Student.
class Student {

    var name = ""
    private var rollNumber = 0

    func uniqueId() {
        print(rollNumber)
    }
}

// How to access it?
let alex = Student()
print("Alex Roll number: \(alex.uniqueId())") // print roll number
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explaination:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;First, we have created a class Student with some variables.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, define a function to read the value of a private variable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a class object called alex and printing his roll number.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note: You can see, rollNumber is a private variable in the class Student, still you can read its value outside the class scope using a public function uniqueId(). Further to note, you can not access variable rollNumber directly like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let alex = Student()
print("Alex Roll number: \(alex.rollNumber)") // error

// here, you will get an error &amp;lt;'rollNumber' is inaccessible due to 'private' protection level&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Using Extensions
&lt;/h2&gt;

&lt;p&gt;The private members of a class, structure, enum, or protocol can be accessed by creating an extension. Here's an example to help you understand:&lt;br&gt;
&lt;/p&gt;

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

  // private variable
  private var name = "Alex John"

  // private method    
  private func displayDetails() {
    print("Full Name: \(name)")
  }
}

// 1. creating object
var studentObject = Student()

// 2. access name property
print("Name:", studentObject.name)

// 3. access displayDetails() method 
studentObject.displayDetails()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explaination:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;In step 1, we created an object for the Student class.&lt;/li&gt;
&lt;li&gt;In step 2, we are trying to read a property called name.&lt;/li&gt;
&lt;li&gt;In step 3, we are calling the method displayDetails().&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Notice in step 2, we are trying to read the value of a private member of the class. While we will access it, we shall get an error like the below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: 'name' is inaccessible due to 'private' protection level

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

&lt;/div&gt;



&lt;p&gt;Same error we shall get while accessing private method of the class like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: 'displayDetails' is inaccessible due to 'private' protection level
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to access them?
&lt;/h2&gt;

&lt;p&gt;You can access private variables and functions of a class using the extension feature provided in Swift.&lt;/p&gt;

&lt;p&gt;** First, lets understand what an extension is in Swift.**&lt;/p&gt;

&lt;p&gt;Extension: Using extension, you can extend a class, structure, enum, or protocol type by adding new functionality to an existing class or structure. Swift's provided classes or custom types can have additional members by using the extension keyword.&lt;/p&gt;

&lt;p&gt;Let's see how extensions can be used to access private members by example:&lt;br&gt;
&lt;/p&gt;

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

    // private variable
    private var firstName = "Alex"
    private var lastName = "John"
    private var city = "California"
    private var rollNumber = "BR546"
}

extension Student {

    func displayDetails() {
        print("First name: \(firstName), city: \(city), and roll number: \(rollNumber)")
    }

    func getFullName() -&amp;gt; String {
        "\(firstName) \(lastName)"
    }
}


// 1. creating object
var studentObject = Student()

// 2. Displaying full name
let name = studentObject.getFullName()
print(name) // Alex John
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: The extension should be in the same Swift file. Extension which defines outside the file, cannot access the private members.&lt;/p&gt;

&lt;h1&gt;
  
  
  3. Using computed properties
&lt;/h1&gt;

&lt;p&gt;Swift provides a computed property feature through which you can access private properties.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Computed Property:&lt;/strong&gt; A computed property, it’s all in the name, computes its property upon request. Adding a new property value based on other conditions can be a valuable addition to any of your types.&lt;/p&gt;

&lt;p&gt;Let's understand how to access private properties using it with the example below:&lt;br&gt;
&lt;/p&gt;

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

    // private variable
    private var firstName = "Alex"
    private var lastName = "John"

    // computed properties
    var fullName: String {
        "\(firstName) \(lastName)"
    }
}

// 1. creating object
var studentObject = Student()

// 2. Displaying full name using computed property
print(studentObject.fullName)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, you can see we are printing full name of the student with the help of computed property called fullName.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Using lower access level with setter
&lt;/h2&gt;

&lt;p&gt;You can give a setter of a lower access level than its corresponding getter, to restrict the read-write scope of that variable, property, or subscript. You assign a lower access level by writing private(set) before the var or subscript introducer.&lt;/p&gt;

&lt;p&gt;Let's understand it by example:&lt;br&gt;
&lt;/p&gt;

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

  // private setter variable
  private(set) var name = "Alex John"

  // private method    
  private func displayDetails() {
    print("Full Name: \(name)")
  }
}

// 1. creating object
var studentObject = Student()

// 2. access name property
print("Name:", studentObject.name) // display: "Alex John"

// 3. assigning a new value
studentObject.name = "Alex Martin" // error
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, you can see how to read a private member's value outside of the class scope using the private(set) setter.&lt;/p&gt;

&lt;p&gt;It is important to note that you cannot change the value of this property as you are restricted from changing it.&lt;/p&gt;

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

&lt;p&gt;Now you understand how to access private members of a class. There are different ways to access them in the code.&lt;/p&gt;

&lt;h2&gt;
  
  
  What next?
&lt;/h2&gt;

&lt;p&gt;In this guide, you learned about accessing private members of a class. We encourage you to read more related topics like &lt;a href="https://www.swiftanytime.com/blog/access-control-in-swift/" rel="noopener noreferrer"&gt;Access Control in Swift&lt;/a&gt;, &lt;a href="https://www.swiftanytime.com/blog/functions-in-swift/" rel="noopener noreferrer"&gt;Functions in Swift&lt;/a&gt;, etc. For more updates, stay tuned. Till then,&lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
      <category>discuss</category>
    </item>
    <item>
      <title>Toggle in SwiftUI</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Mon, 13 Feb 2023 14:18:48 +0000</pubDate>
      <link>https://dev.to/swiftanytime/toggle-in-swiftui-3e6h</link>
      <guid>https://dev.to/swiftanytime/toggle-in-swiftui-3e6h</guid>
      <description>&lt;p&gt;Toggles are some of the most used UIControl in iOS Apps since it lets let you switch between a binary state - true or false, 0 or 1.&lt;/p&gt;

&lt;p&gt;You are most likely to encounter a toggle in settings or some kind of list view. But regardless of your app has settings or not, it doesn't hurt to learn about Toggle in SwiftUI. Before diving into a toggle, let's take a look at Human Interface Guideline.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: This is UIKit equivalent of UISwitch&lt;/p&gt;
&lt;/blockquote&gt;

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

&lt;h1&gt;
  
  
  Takeaways from Human Interface Guideline
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Recommended to use it in table row only.&lt;/li&gt;
&lt;li&gt;Recommended not to add a lot of labels for description.
&lt;a href="https://developer.apple.com/design/human-interface-guidelines/ios/controls/switches/" rel="noopener noreferrer"&gt; Source&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Basic Implementation
&lt;/h1&gt;

&lt;p&gt;For you to implement a basic toggle, you require a binding boolean and a string that would label the string. Let's give it a try.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@State var isOn = false // 1
    var body: some View {
        Toggle("Airplane Mode", isOn: $isOn) // 2
            .padding()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Defining a bool variable isOn which is later used in the toggle init as a Binding.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Displaying a toggle with initialize of label and isOn.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the case you are looking for a custom modifier, you can go for the init with label.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@State var isOn = false
    var body: some View {
        Toggle(isOn: $isOn, label: { // 1
            Label("Airplane Mode", systemImage: "airplane") // 2
        })
            .padding()

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

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Defining toggle with label init.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using a Label with some relevant text and airplane SF symbol.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Styling appearance
&lt;/h1&gt;

&lt;p&gt;You can apply all the style modifiers that are applicable to a SwiftUI view. But there are a couple of styles which are specific to button toggle.&lt;/p&gt;

&lt;p&gt;Eventhough, there are a couple of style which are highlight worthy. One is to use a toggle style of button (by ButtonToggleStyle) and have a button that changes the background color based on the toggle state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       Toggle(isOn: $isOn, label: {
            Label("Airplane Mode", systemImage: "airplane")
        })
            .toggleStyle(ButtonToggleStyle())
            .foregroundColor(.orange)
            .padding()

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

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Another way, which is default and the one that you are most likely to encounter is the toggle switch way where there is a switch and you can turn it off and on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;            Toggle(isOn: $isOn, label: {
            Label("Airplane Mode", systemImage: "airplane")
        })
            .toggleStyle(SwitchToggleStyle())
            .foregroundColor(.orange)
            .padding() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have a switch and you want to change the tint color, you can do it by using tint(...) for iOS 15 and later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct ToggleUI: View {
    @State var isOn = false
    var body: some View {
        Toggle(isOn: $isOn, label: {
            Label("Airplane Mode", systemImage: "airplane")
        })
            .toggleStyle(SwitchToggleStyle())
            .tint(.gray)
            .foregroundColor(.orange)
            .padding()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For iOS 15 or earlier, you can use the following style modifier:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.toggleStyle(SwitchToggleStyle(tint: .gray))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Concluding the article, today you learned about how to integrate a toggle switch in your app and you can customize it in form of a button and change the tint color. &lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to use Gestures In SwiftUI</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Thu, 09 Feb 2023 16:58:38 +0000</pubDate>
      <link>https://dev.to/swiftanytime/how-to-use-gestures-in-swiftui-b0c</link>
      <guid>https://dev.to/swiftanytime/how-to-use-gestures-in-swiftui-b0c</guid>
      <description>&lt;p&gt;Back when we had Blackberry and Nokia phones, everything was based on button clicks. After clicking those chunky keys, you would be able to write the text and use the phone. Got some nostalgia kicking in, huh? Well, that was the scenario back then. When the touch screen phone came, all those chunky keys were gone and everything was based on finger gestures. There are multiple gestures one can perform on a modern cell phone: tap, drag, swipe, pinch, double-tap, rotate, shake, touch and hold, and a lot more. Today, you are going to dive into a few of the essential and most used gestures in SwiftUI.&lt;/p&gt;

&lt;h1&gt;
  
  
  Tap Gestures
&lt;/h1&gt;

&lt;p&gt;These are the most basic gestures. Most of the interactions in modern apps are done through tap gestures. Implementing tap gestures is pretty simple. You call .onTapGesture() on the view you want to track the gesture.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        Text("Hello, World!")
            .onTapGesture {
                print("View Tapped")
            }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;In the above example, every time the view is tapped, "View Tapped" is printed.&lt;/p&gt;

&lt;p&gt;You can also implement action on a certain amount of tap gesture counts. This could be used to having some custom interaction or secret hack (like tapping multiple times to show a shortcut).&lt;/p&gt;

&lt;p&gt;In the following code, every time the text is tapped three times, "View tapped multiple times" is printed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; Text("Hello, World!")
            .onTapGesture(count: 3) {
                print("View tapped mulitple times")
             }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;h1&gt;
  
  
  Long Press Gesture
&lt;/h1&gt;

&lt;p&gt;You can creatively apply long-press gestures. For example, in the Instagram app, long-pressing the play button in the camera will record a video. While performing a tap gesture will take a picture.&lt;/p&gt;

&lt;p&gt;Just like tap gestures, there are long tap gestures where we tap the view for too long. Implementing a basic long press gesture is quite similar to implementing a tap gesture (as given above).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  Button {
            print("Button Tapped")
        } label : {
        Label("Start", systemImage: "play") // 1 
        }
            .padding()
            .foregroundColor(.black)
            .background(Color.orange)
            .cornerRadius(10)
            .onLongPressGesture  { 
                print("Long Press Gesture") // 2 
            }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Here, there is the use of label with SF Symbol image and "Start" as the text.&lt;/li&gt;
&lt;li&gt;Adding the modifier so that when a long process gesture is detected, it prints "Long Press Gesture".&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;As expected, on long press of the view, the compiler prints "Long Press Gesture". But what if you want some specific time limit? Or what if you want to have some custom UI when the view is being pressed? For that, onLongTapGesture comes with minimumDuration parameter to add minimum time limit and onPressingChange method which takes a boolean.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; @State var backgroundColor = Color.orange
    var body: some View {

        Label("Start", systemImage: "play")
            .padding()
            .background(backgroundColor) // 1 
            .cornerRadius(10)
            .onLongPressGesture(minimumDuration: 3) { isPressing in // 2 
                if isPressing == true { // 3 
                    self.backgroundColor = .red
                } else {
                    self.backgroundColor = .orange
                }
            } perform: { // 4 
                print("Long Press Gesture")
            }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Adding variable background so one can change it programmatically.&lt;/li&gt;
&lt;li&gt;Here, the long press gesture is given a minimum duration of 3 seconds. So, the long press is detected in 3 seconds.&lt;/li&gt;
&lt;li&gt;When the press state change is detected, the bool (isPressing) is checked. If isPressing is true, the background is red or orange.&lt;/li&gt;
&lt;li&gt;Prints "Long Press Gesture" on long-press gesture.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Magnification Gesture
&lt;/h1&gt;

&lt;p&gt;When working on making standard media (mostly images and videos) in SwiftUI, you would most probably deal with magnification for zooming onto images and videos.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  @State var zoomScale = 1.0 // 1 
    var body: some View {

        Image(systemName: "photo.fill") // 2 
            .resizable()
            .aspectRatio(contentMode: .fill)
            .frame(width: 100, height: 100)
            .scaleEffect(zoomScale) // 3 
            .gesture( // 4 
            MagnificationGesture()
                .onChanged({ amount in
                   zoomScale += amount 
                })
        )

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

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;blockquote&gt;
&lt;p&gt;Note: You can simulate two-finger actions in the simulator by clicking Option button.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The zoom scale is stored in the variable. The default value is 1.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Here, you add an image that is resizable, with a 100x100 frame and fill content mode.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The scale of the is set to zoomScale. We are later going to change this value when the magnification gesture happens.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Here, the magnification gesture is added to the view and on change, the magnification value of image is added to zoomValue. This will cause the zoom effect.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here, this doesn't allow to zoom back in or have smooth gestures since that is more of an intermediate topic. That is a discussion for another SwiftAnytime article.&lt;/p&gt;

&lt;p&gt;Though, this is not where the topic ends. This is a broad topic with multiple gestures and their application. Like, you could implement a pan gesture on the home screen and implement an Instagram-like home screen-swipe gesture by tracking the translation. Or you could use drag gestures for the interaction of arranging certain files in your app.&lt;/p&gt;

&lt;p&gt;Wrapping up the article piece, today you learned about tap gesture, long-press gesture and magnification gesture. Till then,&lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>What is Trailing closure in Swift?</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Wed, 08 Feb 2023 13:23:17 +0000</pubDate>
      <link>https://dev.to/swiftanytime/what-is-trailing-closure-in-swift-1431</link>
      <guid>https://dev.to/swiftanytime/what-is-trailing-closure-in-swift-1431</guid>
      <description>&lt;p&gt;As per the standard definition, Closures are self-contained blocks of functionality that can be passed around and used in your code.&lt;br&gt;
When passing a closure expression to a function as the function’s final argument, it can be useful to write a trailing closure.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Trailing closure is written after the function call’s parentheses even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h1&gt;
  
  
  Syntax
&lt;/h1&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Note: This function accepts a closure as it's final argument
func functionName(closure: () -&amp;gt; Void) {
    // function body goes here
}

// Calling this function without using a trailing closure:

functionName(closure: {
    // closure's body goes here
})

// Calling this function with a trailing closure:

closure() {
    // trailing closure's body goes here
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Note: 1. When using the trailing closure syntax, we don’t write the argument label for the first closure as part of the function call.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A function call can include multiple trailing closures.&lt;/li&gt;
&lt;li&gt;The parameters to functions and closures are always constants.&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;
  
  
  Examples
&lt;/h1&gt;

&lt;p&gt;Swift’s standard library provides a method called sorted(by:), which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sorted(by:) method returns a new array of the same type and size as the old one, with its elements in the correct sorted order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Calling sorted function without trailing closure
ascending = salaries.sorted(by: {s1: Int, s2: Int) -&amp;gt; Bool in
    return s1 &amp;lt; s2
})

//Calling trailing function with closure
ascending = salaries.sorted() { s1, s2 in s1 &amp;lt; s2 }

//Since closure is the only argument here, paratheses can be dropped as:
ascending = salaries.sorted {s1, s2 in s1 &amp;lt; s2 }

//Using shorthand arguments (explained previously):
ascending = salaries.sorted {$0 &amp;lt; $1}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we see how writing trailing closures, especially when the closure expression is long can make the code more readable.&lt;/p&gt;

&lt;p&gt;In the next example, we understand how to use multiple trailing closures. The function makes a network call using the given URL and based on the outcome, the respective trailing closure is used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Example using multiple trailing closures

//Function call that makes an API call and returns result only if the API call is successful
func triggerAPICall(from url: URL, completion: (Result)-&amp;gt;Void, onFailure: ()-&amp;gt;Void) {
//make API call from given URL
...
if let result.status = .success {
completion(result)
} else {
onFailure()
}
}

//Calling the function above:
triggerAPICall(from: url) { result in 
///parse result and reload view
...
} onFailure: {
print("Oops! Something went wrong")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Writing the function this way lets you cleanly separate the code that’s responsible for handling a network failure from the code that updates the user interface after a successful download, instead of using just one closure that handles both circumstances.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;Trailing closures are commonly used as completion handlers, i.e. to handle completion of network calls (as explained in the example above) and other such tasks. To know more about escaping, non-escaping closures, capture lists, etc. continue reading this article series. &lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>ProgressView in SwiftUI</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Tue, 07 Feb 2023 15:18:09 +0000</pubDate>
      <link>https://dev.to/swiftanytime/progressview-in-swiftui-17ep</link>
      <guid>https://dev.to/swiftanytime/progressview-in-swiftui-17ep</guid>
      <description>&lt;p&gt;Almost everyone hates the buffering screen we get due to low internet or the app processing something. Well, but since 5G is here in India, there are less chances of you spending your day just staring at a progress view.&lt;/p&gt;

&lt;p&gt;Even though we all hate it, making a progress view in your app is inevitable and at some point, you would have to use it in our app. May it be for showing process while you save something to CoreData or to show progress while you are getting something from URLSession.&lt;/p&gt;

&lt;p&gt;Looking back at UIKit, you would use UIActivityIndicator for showing a spinner and UIProgressView for showing a linear progress bar in your app. In SwiftUI, you can implement both of these types of progress view in your app using ProgressView.&lt;/p&gt;

&lt;p&gt;Without further ado, let’s dive into the human interface guidelines summary first.&lt;/p&gt;

&lt;h1&gt;
  
  
  Summary of Human Interface Guidelines
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: Determinate Progress View means a progress view with a task with well known duration. While Indeterminate Progress View means a progress view with a unquantifiable task and unknown duration.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If possible, use determinate progress view.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When possible, give people option to stop the process. When stopping the process has a negative consequence, let people know or give a confirmation alert dialogue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Stick to one progress bar style - circular or bar style.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Keep the progress bar moving to let people know the progress.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Show it at consistent location.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Source: &lt;a href="https://developer.apple.com/design/human-interface-guidelines/components/status/progress-indicators/" rel="noopener noreferrer"&gt;Apple&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Basic implementation
&lt;/h1&gt;

&lt;p&gt;Let's make a basic progress view - also called circular progress view.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ProgressView("Processing") // 1&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;1.Using a ProgressView with string initializer.&lt;/p&gt;

&lt;p&gt;Pretty simple to implement, right?&lt;/p&gt;

&lt;p&gt;There are two types of styles availabe. One is the circular style (the default progress view style) which you tried above. The second is linear progress bar which updates according to the value given. You are most likely to encounter the latter while displaying download tasks or something similar.&lt;/p&gt;

&lt;p&gt;So let's try to implement a linear progress bar that updates regularly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@State var value : Float = 0
    var body: some View {
    // 1 
        ProgressView("Processing", value: value, total: 100)
            .progressViewStyle(LinearProgressViewStyle())
            .padding()
            .onAppear {
            // 2
                Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
                    self.value += 1
                }
            }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Using ProgressView with the title "Processing", setting the current value of the progress bar to value and the total value of the progress bar to 100.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For simplicity sake, on appear, you use a timer and increase value by 1, every second. In real life, you could update the value while loading a URLSession data task or something similar to that.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Styling
&lt;/h1&gt;

&lt;p&gt;There is not a lot that you can customize in this but the most handy style modifiers are tint and foregroundColor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      ProgressView("Processing")
            .tint(.orange) // 1 
            .foregroundColor(.gray) // 2 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Setting tint color to orange. This will set the spinning view to orange.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Setting foreground color to gray. This will set the label color to gray.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can also apply the same to the linear progress bars.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  ProgressView("Processing")
            .progressViewStyle(LinearProgressViewStyle()) // 1 
            .tint(.orange)
            .foregroundColor(.gray)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Setting the progress view style to linear progress bar.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Wrapping up, today you learned about how to show a progress bar in a couple of ways (linear progress bar and circular progress bar) and about stylizing the appearance.&lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
      <category>blockchain</category>
      <category>web3</category>
      <category>crypto</category>
      <category>offers</category>
    </item>
    <item>
      <title>How to dismiss the keyboard in SwiftUI</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Mon, 06 Feb 2023 12:36:06 +0000</pubDate>
      <link>https://dev.to/swiftanytime/how-to-dismiss-the-keyboard-in-swiftui-1fac</link>
      <guid>https://dev.to/swiftanytime/how-to-dismiss-the-keyboard-in-swiftui-1fac</guid>
      <description>&lt;p&gt;When dealing with forms and more, it is likely that you would encounter a scenario where you would want to dismiss the keyboard programmatically ie. on click of "Submit" or "Next" button. Without further ado, let's explore a couple of ways to dismiss the keyboard in SwiftUI.&lt;/p&gt;

&lt;h1&gt;
  
  
  Using App Delegate Methods
&lt;/h1&gt;

&lt;p&gt;One of the easiest way is to use app delegate method and calling the endEditing() on UIApplication. This method will resign the first responder of the view (which, in this case, is the textfield's keyboard).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@State var name : String = ""
    var body: some View {
        VStack {
            TextField("Enter name here", text: $name)
            Button {
                dismissKeyboard() // 1
            } label : {
                Text("Dismiss Keyboard") // 2
            }
        }.padding() // 3

    func dismissKeyboard() {
      UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.endEditing(true) // 4
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Calling the dismiss keyboard method on the click of "Dismiss Keyboard" button.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Setting a label of text "Dismiss Keyboard" of the button.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adding padding to the view.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining dismissKeyboard() function which ends editing on UIApplication.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  @FocusState for iOS 15+
&lt;/h1&gt;

&lt;p&gt;The above method requires you to directly interact with the UIApplication method. If you are looking for more SwiftUI-like method to do the same, you can try the FocusState method. The only fallback of this method is that it's only available for iOS 15 and later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@State var name : String = ""
  @FocusState var isFocused : Bool // 1 
    var body: some View {
        VStack {
            TextField("Enter name here", text: $name)
                .focused($isFocused) // 2 
            Button {
                isFocused = false // 3 
            } label : {
                Text("Dismiss Keyboard")
            }
        }.padding()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

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

&lt;h1&gt;
  
  
  Code Explanation:
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Defining a @FocusState bool variable. Observe that we are not defining a value to it and rather just assigning it the type of Bool.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adding the style modifier of to the textfield and assigning it the binding variable of isFocused variable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Setting the isFocused value to false on the "Dismiss Keyboard" button click.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The above method works when you have one textfield on the screen. Let's take a look at a case when there are multiple textfields on the screen.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 1 
    @FocusState var isEmailFocused : Bool 
    @FocusState var isNameFocused : Bool 

   // 2 
    @State var email : String = ""
    @State var name : String = ""

    var body: some View {
        VStack(spacing: 20) { // 3 
        // 4 
            TextField("Enter name here", text: $name) 
                .focused($isNameFocused)
            TextField("Enter email here", text: $email) 
                .focused($isEmailFocused)

            Button("Dismiss Current TextField") { // 5 
                if isNameFocused {
                    isNameFocused = false
                } else if isEmailFocused {
                    isEmailFocused = false
                }
            }

        }.padding()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/..." class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/..." alt="Uploading image" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Defining individual focus state variables for email and name variable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining string variables for name and email field&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining a VStack with spacing set to 15&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Showing textfields with text and focus state set to the corresponding variable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Showing a button with text initializer. On tap, the button checks if the isNameFocused is true. If so, it toggles isNameFocused, else if checks if if email is focused and sets it to false.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Congratulations! Today you learned about two ways to dismiss keyboard in SwiftUI - using UIApplication editing method and by using Focus State variable (available for iOS 15 or later) for both single and multiple textfields in the screen. Till then,&lt;/p&gt;

&lt;p&gt;Eat. Swift. Swift Anytime. Repeat.&lt;/p&gt;

</description>
      <category>devto</category>
      <category>announcement</category>
      <category>community</category>
      <category>offers</category>
    </item>
    <item>
      <title>View Controller Lifecycle</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Thu, 02 Feb 2023 15:51:19 +0000</pubDate>
      <link>https://dev.to/swiftanytime/view-controller-lifecycle-4kbk</link>
      <guid>https://dev.to/swiftanytime/view-controller-lifecycle-4kbk</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;In iOS development, the view controllers are the foundation of the Application's internal structure. The View Controller is the parent of all the views present on a storyboard. Each UIKit application has at least one ViewController. It facilitates the transition between various parts of the user interface.&lt;/p&gt;

&lt;p&gt;Functions are called in the following order when a View Controller is added to the view hierarchy:&lt;/p&gt;

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

&lt;h1&gt;
  
  
  State Transition Functions
&lt;/h1&gt;

&lt;h1&gt;
  
  
  viewDidLoad()
&lt;/h1&gt;

&lt;p&gt;This is called after the view is loaded in to memory, and is commonly thought of as the first method that will be called. Majority of the view configurations and API setups are done here.&lt;/p&gt;

&lt;h1&gt;
  
  
  viewWillAppear(_: )
&lt;/h1&gt;

&lt;p&gt;This method is called use before the View Controller is added to the view hierarchy. The frame and bounds of the view controller are all set. This function is called each time the view is presented on screen.&lt;/p&gt;

&lt;h1&gt;
  
  
  viewWillLayoutSubviews()
&lt;/h1&gt;

&lt;p&gt;When the view controller's view is changed in its layout or bounds, then the system will call a viewWillLayoutSubviews. Thus, this function can be called multiple times during the life of the View Controller. Your view controller can override this method to make changes before the view lays out its subviews.&lt;/p&gt;

&lt;h1&gt;
  
  
  viewDidLayoutSubviews()
&lt;/h1&gt;

&lt;p&gt;viewDidLayoutSubviews is called every time the view is done with autolayout calculations. It is also called if the view is updated, rotated, changed or its bounds change. This function is important, especially, when the orientation of device is changed to add some implementation after views are updated.&lt;/p&gt;

&lt;h1&gt;
  
  
  viewDidAppear(_: )
&lt;/h1&gt;

&lt;p&gt;This function is called just after the View Controller is added to the view hierarchy. The users can see the view at this point, hence, animations can be started here.&lt;/p&gt;

&lt;p&gt;Note: viewDidLoad() is only called once when the view is loaded. Wherever, viewDidappear() is called everytime the view appears on the screen.&lt;/p&gt;

&lt;h1&gt;
  
  
  viewWillDisappear(_: )
&lt;/h1&gt;

&lt;p&gt;This is a good place to save user data and cancel network tasks since it is called just before it is about to disappear from the view hierarchy.&lt;/p&gt;

&lt;h1&gt;
  
  
  viewDidDisappear(_: )
&lt;/h1&gt;

&lt;p&gt;This function is called when the view disappears from the view hierarchy. Thus, the view is already disappeared from the user's view. Tasks like cancelling the data or ending the analytic events can be performed once the view is disappeared.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;Understanding the life cycle functions are important to make the most of these functions. Life Cycle functions and state transitions can be summarised as:&lt;/p&gt;

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

&lt;p&gt;Note: This is a highly asked basic interview question.&lt;/p&gt;

&lt;p&gt;Congratulations! You have understood the highly important fundamental topic of UIKit.&lt;/p&gt;

</description>
      <category>cryptocurrency</category>
      <category>web3</category>
      <category>blockchain</category>
    </item>
    <item>
      <title>Action Sheets in SwiftUI</title>
      <dc:creator>Swift Anytime</dc:creator>
      <pubDate>Wed, 01 Feb 2023 17:16:16 +0000</pubDate>
      <link>https://dev.to/swiftanytime/action-sheets-in-swiftui-gnc</link>
      <guid>https://dev.to/swiftanytime/action-sheets-in-swiftui-gnc</guid>
      <description>&lt;p&gt;Action Sheets allow you to show a popover over the current view presenting the user with certain options to select. In SwiftUI, you can implement action sheets using .actionSheet view modifier. You can observe the usage of action sheets through iOS, specially in events while confirming actions.&lt;/p&gt;

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

&lt;p&gt;So without further ado, let's dive in and explore about action sheets. But before that, it is important to follow right practices, so let's look into what Apple's Human Interface Guideline says.&lt;/p&gt;

&lt;h1&gt;
  
  
  Best Practices
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It is expected not to have too many options in your action sheet because it can confuse people for making decisions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Always provide a button to dismiss the action sheet (Usually “Cancel”).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If your action sheet has any confirmation of destruction, do highlight it in red in order to make it noticeable.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Implementing action sheet
&lt;/h1&gt;

&lt;p&gt;For showing an action sheet, all you need is a title and a description (optional) and a bunch of action sheet options.&lt;/p&gt;

&lt;p&gt;Just like alerts, there are three kinds of buttons in alert action.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Default: Default style.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cancel: Indicating to dismiss the alert action and leave things unchanged.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Destructive: Red-colored button indicating some kind of destruction ie. deletion or removal.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s make an alert action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct ContentView: View {
    @State var showActionSheet = false // 1 
    @State var coffeeConsumptionTime = "" // 2
    var body: some View {
        Button {
            self.showActionSheet = true // 3 
        } label: {
            Text("Show action sheet") 
        }
            .actionSheet(isPresented: $showActionSheet) { 
             ActionSheet(title: Text("When do you usually consume your coffee?"), message: nil, buttons: [ // 4
                .default(Text("Morning"), action: { // 5
                    self.coffeeConsumptionTime = "Morning"
                }),
                .default(Text("Afternoon"), action: {
                    self.coffeeConsumptionTime = "Afternoon"
                }),
                .default(Text("I dont lol"), action: {
                    self.coffeeConsumptionTime = ""
                }),
                .cancel() // 6
             ]
             )
            }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result:&lt;/strong&gt;&lt;/p&gt;

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

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Defining state variable showActionSheet which you are going toggle later for showing action sheets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining state variable coffeeConsumptionTime for storing user's preference.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Setting showActionSheet to true on click of the button.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining ActionSheet variable with a title and assigning bunch of buttons.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining a default action button type and setting coffeeConsumptionTime as the action.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining the cancel button.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;Fun fact: If you add two cancel buttons, the app will crash when showing the alert action. Try it yourself.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;
  
  
  Updates in action sheet in iOS 15
&lt;/h1&gt;

&lt;p&gt;After iOS 15.2, Apple deprecated alertAction and introduced confirmationDialog for the same purpose.&lt;/p&gt;

&lt;p&gt;So, let’s try to replicate the above alert action in confirmation dialog.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.confirmationDialog("", isPresented: $showActionSheet) { // 1 
            Button("Morning") {  // 2 
                self.coffeeConsumptionTime = "Morning"
            }
            Button("Afternoon") {
                self.coffeeConsumptionTime = "Afternoon"
            }
            Button("I dont lol") {
                self.coffeeConsumptionTime = ""
            }
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;&lt;strong&gt;Code Explanation:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Defining the confirmationDialog style modifier and assigning a binding variable to it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Here, you are defining bunch of buttons with certain label and action.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Also, note here that inspite of that fact that we did not add a cancel button, it showed up the result. Cancel button is automatically generated by confirmation dialog.&lt;/p&gt;

&lt;p&gt;Instead of using the Alert Action button, we use the native buttons here. Note that here, we didn’t add the “Cancel” button. It was added by default by SwiftUI.&lt;/p&gt;

&lt;p&gt;Congratulations! Today you learned about the basic implementation of action sheets (for both iOS 15+ and under iOS 15) and different styles of action button styles.&lt;/p&gt;

&lt;p&gt;Eat. Sleep. Swift Anytime. Repeat.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
