<?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>Forem: Kate</title>
    <description>The latest articles on Forem by Kate (@kduncanwelke).</description>
    <link>https://forem.com/kduncanwelke</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%2F488305%2Fa9cbc4f8-f6ad-4c31-a9d8-52c98d17bb3f.jpg</url>
      <title>Forem: Kate</title>
      <link>https://forem.com/kduncanwelke</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kduncanwelke"/>
    <language>en</language>
    <item>
      <title>Revisiting past projects</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Mon, 15 Mar 2021 22:11:34 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/revisiting-past-projects-31o8</link>
      <guid>https://forem.com/kduncanwelke/revisiting-past-projects-31o8</guid>
      <description>&lt;p&gt;Revisiting old projects is a great way to improve your skills and reaffirm and contribute to your overall progress as a coder.&lt;/p&gt;

&lt;p&gt;A previously completed project that fulfilled its purpose at the time it was finished but has since remained untouched can be a goldmine for improvement. Re-assessing old code after some time has elapsed can help you see places where there is room for improvement, whether in structure, approach, or a different approach to a problem. &lt;/p&gt;

&lt;p&gt;It's easy to make mistakes early on as a beginner (because there ie still so much to learn), but these missteps are easy to spot later on when you have more experience. Taking a fresh look at an old project gives you an opportunity to update it with solutions and gain confidence in applying the coding concepts you employed as part of the fix.&lt;/p&gt;

&lt;p&gt;As a developer, supplying and responding to constructive criticism - whether your own or others' - is a valuable ability, and practicing on your past projects is a great way to show you have the focus and self awareness to do so. &lt;/p&gt;

&lt;p&gt;By reworking old code that worked but wasn't ideal to be more compatible with your language (Swift should be Swifty, which means no reliance upon hard-coded values, etc) to be DRYer, more efficient, and better structured, you demonstrate an ability to look at your work objectively and see where it requires improvement. &lt;/p&gt;

&lt;p&gt;As developers we always strive to learn something new, and putting that knowledge into action by integrating it into an existing project is also a great way to demonstrate it. For example, I have reworked two projects from an original MVC (Model View Controller) design pattern into MVVM (Model View ViewModel) over the past few months, in order to cement MVVM into my mind and simply the two apps I worked on.&lt;/p&gt;

&lt;p&gt;If you have old projects that are sitting around gathering dust, you may want to consider revisiting a few of them as well - they are a great opportunity to demonstrate your progress, practice self-critique, and put new knowledge into practice.  &lt;/p&gt;

</description>
    </item>
    <item>
      <title>It's here!</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Fri, 16 Oct 2020 22:08:14 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/it-s-here-59hb</link>
      <guid>https://forem.com/kduncanwelke/it-s-here-59hb</guid>
      <description>&lt;p&gt;The new release of &lt;a href="https://apps.apple.com/us/app/id1503747823"&gt;Calm Cloud&lt;/a&gt; has arrived! With new season and weather environments the gamified lifestyle stress-reduction app is better than ever!&lt;/p&gt;

&lt;p&gt;This one was a long haul to create, but well worth the effort, especially if its being out in the world helps people. We're all running with a constant underlying level of stress lately, so I created Calm Cloud to try to help diffuse some of those worries.&lt;/p&gt;

&lt;p&gt;It features a creature called a cloud kitty, who is named Zen, a friendly little interior environment, and an outdoor garden where you can grow, water, and harvest plants! It also has some practical features like reminders, a list of calming/productive activities, a thankfulness journal, and an area to collect photos of some of your favorite things (like in the song from &lt;em&gt;The Sound of Music&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Throughout there are calming ambient sounds and fun interactive pieces, such as lights that turn on and off, playable music, toys that move, and more. Further updates will be coming to Calm Cloud in time! If you'd like to keep up with its commits you can see the code on GitHub &lt;a href="https://github.com/kduncanwelke/Calm-Cloud"&gt;here&lt;/a&gt;! ✨&lt;/p&gt;

</description>
      <category>swift</category>
      <category>iosdevelopment</category>
      <category>iosapp</category>
    </item>
    <item>
      <title>MVC to MVVM in Swift</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Mon, 12 Oct 2020 22:53:02 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/mvc-to-mvvm-in-swift-2j7m</link>
      <guid>https://forem.com/kduncanwelke/mvc-to-mvvm-in-swift-2j7m</guid>
      <description>&lt;p&gt;I recently converted my first App Store approved app (Exhibit Finder DC) from the MVC to MVVM instead. MVC - Model View Controller - and MVVM - Model View ViewModel - are both design patterns; essentially methods of organization used within your app. &lt;/p&gt;

&lt;p&gt;MVC is the design pattern which is typically taught first in Swift, and is generally speaking what Apple encourages developers to use. It consists of a Model that holds the data, a View that the user interacts with, and a Controller which acts as a go-between for the other two. &lt;/p&gt;

&lt;p&gt;User actions in the View go through the Controller, which will provide the View with updates as needed. The Controller also updates the Model with changes, and the Model notifies the Controller if it has its own changes. Essentially the View and the Model never talk to each other directly (maybe they were estranged long ago) - their updates only get passed to each other via the Controller. The Model doesn't know what the View is doing, and the View can't tell what the Model is doing either. Each only knows what the Controller tells it.&lt;/p&gt;

&lt;p&gt;In a common MVC setup in an Xcode project, a ViewController is the controller, the storyboard contains the View(s), and the Model is a class/struct which contains the data. This system works, and is easy enough to learn and implement, but it is by no means the only option out there. &lt;/p&gt;

&lt;p&gt;MVC has earned a nickname of 'Massive View-Controller' from iOS developers in general, since the reliance upon the ViewController acting as a go-between for the View and Model often causes it to become bloated with code, and overburdened with responsibility. The unwieldy file then becomes hard to navigate and maintain, especially if the project grows.&lt;/p&gt;

&lt;p&gt;This is where other design patterns can come into play. You may have seen some other abbreviations mentioned before, such as MVVM, VIP, MVP, and more - these other design patterns offer some options for solutions to the MVC problem. I'll focus on MVVM here, but I'd encourage you to learn more about the others too!&lt;/p&gt;

&lt;p&gt;MVVM stands for Model View ViewModel, and consists of a Model for the data, a View the user interacts with, and a new piece - the ViewModel, which handles all manipulations of and interactions with the data. In this case we do still have a ViewController in the code, but its responsibilities are much diminished and it is only alluded to generally in the View part of the MVVM name.&lt;/p&gt;

&lt;p&gt;MVVM is a helpful design pattern to use, since it better delegates responsibility in your project and abstracts the code out into user-friendly sections. Here, there is no longer any business logic in the controller. Its sole responsibility is to take care of the functionality of the View, and work those outlets and actions. &lt;/p&gt;

&lt;p&gt;The Model holds onto all of the data, as before, but it does not perform any work on it. The ViewModel handles all manipulations of the data and gets data from the Model, but the only thing it knows about the Model; it is ignorant of the controller and never touches any of the controller actions etc and has no influence on the View. &lt;/p&gt;

&lt;p&gt;When the controller needs to display data, it asks the ViewModel to give it what it needs, and the ViewModel gets that data from the Model, then passes it along. What the controller then does with that feedback is outside of the range of the ViewModel's knowledge, however.&lt;/p&gt;

&lt;p&gt;Switching a MVC project over to be a MVVM one instead can be a bit daunting, but here are a few things to keep in mind while in the midst of the rearrangement:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;There should be no business logic in the view controller&lt;/li&gt;
&lt;li&gt;The view controller should only handle appearance/the view&lt;/li&gt;
&lt;li&gt;The model should simply hold onto the data&lt;/li&gt;
&lt;li&gt;The view model should handle all manipulation of the data&lt;/li&gt;
&lt;li&gt;The view model should not be aware of the controller&lt;/li&gt;
&lt;li&gt;The controller does not access data, but asks the view model for it&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope this summary helps you see the essential differences between MVC and MVVM, and how you might use each! If you'd like to see specifically how a project changes from MVC to MVVM, please check out my &lt;a href="https://github.com/kduncanwelke/Exhibit-Finder"&gt;Exhibit Finder DC repo&lt;/a&gt;, and see the difference between the older version and the new one! Happy coding!&lt;/p&gt;

</description>
      <category>swift</category>
      <category>designpatterns</category>
      <category>mvc</category>
      <category>mvvm</category>
    </item>
    <item>
      <title>Core Data</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Mon, 12 Oct 2020 21:08:19 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/core-data-nnm</link>
      <guid>https://forem.com/kduncanwelke/core-data-nnm</guid>
      <description>&lt;p&gt;If you have ever entered information into an app that was persisted (existed across app launches) and that wasn’t stored on a server online, chances are it was saved using &lt;a href="https://developer.apple.com/documentation/coredata"&gt;Core Data&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Core Data allows saves, edits, and deletions of data within your app, which lives inside of a data store. Information is stored in Core Data as objects - these can have multiple attributes of different types, as well as having relationships to other objects that can determine their behavior. &lt;/p&gt;

&lt;p&gt;There is a lot you can do with Core Data, but this tutorial will focus on the basics - creating a data model, a managed object context, and persistent store, then saving, editing, and deleting data. We will create a very simple app that allows you to enter a name, which it will use to provide a customized greeting.&lt;/p&gt;

&lt;p&gt;Start by creating a new single-view project, but be sure to leave the ‘Use Core Data’ box unchecked. We’re going to write our own code so we don’t want that boilerplate.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--59Q8GsRw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2xwwhnbxve6c7yjak7z6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--59Q8GsRw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2xwwhnbxve6c7yjak7z6.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that you have your project, let’s create the data model. Create a new file and select data model as the type (scroll down to find it):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o0kyigsN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/etx2nsut9ctka7j6r5wv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o0kyigsN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/etx2nsut9ctka7j6r5wv.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With the data model created, you should be taken to a screen where you can add entities to the model. Click ‘Add Entity’ at the bottom.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nWmrO8m3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2ohl8n7t950t49qhk7el.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nWmrO8m3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/2ohl8n7t950t49qhk7el.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There will now be an entity in the list on the left. Double click its name and change it to something meaningful. I’m going to name mine SavedData. Now our entity needs an attribute - just like structs have attributes, the Core Data entity needs a way to hold values. &lt;/p&gt;

&lt;p&gt;Click the plus sign under the empty attributes list, or the one down at the bottom of the view. A blank attribute will be added to your entity. We plan to save a name here, so give the attribute a proper title, and a type of String. Here is our work so far:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QCYF7fqO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/lf07urmefujy0h1r03t8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QCYF7fqO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/lf07urmefujy0h1r03t8.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our entity is very bare-bones so this step is complete. Time to add a manager to handle the managedObjectContext and persistentContainer. These allow our code to connect to the Core Data model and actually use it.&lt;/p&gt;

&lt;p&gt;Let’s add a new Swift file called CoreDataManager. At the top of the file, be sure to import CoreData. We’ll create a class with the same name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CoreDataManager {
      static var shared = CoreDataManager()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Shared makes this object a singleton, which guarantees it exists as only one object and can be accessed anywhere. Now add the managedObjectContext and persistentContainer inside the CoreDataManager class, both declared as lazy variables so they aren’t instantiated until they are needed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lazy var managedObjectContext: NSManagedObjectContext = { [unowned self] in
        var container = self.persistentContainer
        return container.viewContext
        }()

    private lazy var persistentContainer: NSPersistentContainer = {
        var container = NSPersistentContainer(name: "Model")

        container.loadPersistentStores() { storeDescription, error in
            if var error = error as NSError? {
                fatalError("unresolved error \(error), \(error.userInfo)")
            }

            storeDescription.shouldInferMappingModelAutomatically = true
            storeDescription.shouldMigrateStoreAutomatically = true
        }

        return container
}()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that the container name matches the name of the data model - if you chose a different name, be sure to use it here instead. The NSPersistentContainer handles accessing the model and context, while the NSManagedObjectContext handles changes. The managedObjectContext is declared with [unowned self] to prevent a reference cycle.&lt;/p&gt;

&lt;p&gt;With the CoreDataManager created, we can set the rest of our code. First we’ll create a struct that will hold the loaded data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Name {
    static var loaded: SavedData?
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The static variable is an optional of the entity type created earlier, SavedData. When loading from the managedObjectContext, if an instance of SavedData exists, we will add it to this static variable. By then checking whether loaded is nil or not, we’ll know if there is a name that was loaded.&lt;/p&gt;

&lt;p&gt;The save code added to the ViewController places the loaded data, should it exist, into loaded, and changes the greeting label to use the name. The fetch request uses the entity name to know what to retrieve, in this case our SavedData entity. Because the fetch request returns data in an array, we have to access the first item to get the SavedData object. This is where we first use the loaded variable in the Name struct too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func loadName() {
          var managedContext = CoreDataManager.shared.managedObjectContext
          var fetchRequest = NSFetchRequest(entityName: "SavedData")

          do {
              var result = try managedContext.fetch(fetchRequest)
              if let data = result.first {
                  Name.loaded = data
                  updateGreeting()
              }
              print("loaded")

          } catch let error as NSError {
              // handle error
          }
     }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By calling loadName in viewDidLoad we check right away if there is a save, and update the greeting label. The save button title is altered too, to indicate that there is an existing name, and any newly entered name will overwrite the previous. With the first app launch, however, there will be no name information to load, and there won’t be until the user makes an entry.&lt;/p&gt;

&lt;p&gt;To be able to load something, we have to perform a save operation after the user has entered a name, and tapped the save name button. Here is the code I am using, including the above mentioned function to update the greeting, which will be run whenever the name is changed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func updateGreeting() {
     if let name = Name.loaded?.name {
          greetingLabel.text = "Hello \(name)!"
              saveButton.setTitle("   Resave Name   ", for: .normal)
     } else {
          greetingLabel.text = "Hello!"
          saveButton.setTitle("   Save Name   ", for: .normal)
     }
}

  func saveName() {
          var managedContext = CoreDataManager.shared.managedObjectContext

          // if there is no text in the textField, don't continue
          guard let enteredText = textField.text else { return }

          guard let currentName = Name.loaded else {
              let nameSave = SavedData(context: managedContext)

              nameSave.name = enteredText
              Name.loaded = nameSave

              do {
                  try managedContext.save()
                  print("saved")
              } catch {
                  // handle errors
              }

              updateGreeting()
              textField.text = nil
              return
          }

          currentName.name = enteredText
          Name.loaded = currentName

          do {
              try managedContext.save()
              print("saved")
          } catch {
              // handle errors
          }

          updateGreeting()
          textField.text = nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This save function checks first that the textField has valid text - if it is blank, we want to return and quit the save process. The function then checks if Name.loaded is nil using a guard statement. If it is, it creates a new SavedData entity (since no entity will currently exist in this case) and saves it, then exits at the return. If Name.loaded is not nil (ie currentName has a value) then currentName has the name reassigned, and is then resaved. At the end of both of these paths, the greeting is updated and the textField text is reset so another name can be entered easily.&lt;/p&gt;

&lt;p&gt;Lastly, we need a function that will delete the name entirely.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func deleteName() {
          var managedContext = CoreDataManager.shared.managedObjectContext

          guard let toDelete = Name.loaded else { return }
          managedContext.delete(toDelete)

          do {
              try managedContext.save()
              print("delete successful")
          } catch {
              print("Failed to save")
          }

          Name.loaded = nil
          updateGreeting()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function is called when the delete button is pressed. If Name.loaded doesn’t have a value, then the function exits at the return, as there is nothing to delete. Once the deletion has completed, Name.loaded is reset to nil, since there is no longer an existing save.&lt;/p&gt;

&lt;p&gt;If you run the app, and have set up all the interface as I have, you will see that entering a name changes the label, and you can enter a new name, which will overwrite the previous one, or delete it (have no name shown). Entering a name, saving it, then relaunching the app will cause it to be loaded and the greeting with the name will be shown on the screen. &lt;/p&gt;

&lt;p&gt;This is part of the power of Core Data - its persistence. With some of your own, you can learn to create even more complex models and take advantage of object relationships and more! Happy coding!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/kduncanwelke/SayHello"&gt;Download the project here!&lt;/a&gt;&lt;/p&gt;

</description>
      <category>swift</category>
      <category>iosdevelopment</category>
      <category>coredata</category>
    </item>
    <item>
      <title>Enumerations in Swift</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Mon, 12 Oct 2020 20:46:42 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/enumerations-in-swift-4od7</link>
      <guid>https://forem.com/kduncanwelke/enumerations-in-swift-4od7</guid>
      <description>&lt;p&gt;Let’s talk about one of my favorite things in Swift - enumerations (or enums for short). An &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html"&gt;enumeration&lt;/a&gt; allows you to create a specific and limited set of associated values. They can be applied readily in a situation where an element will be limited by a strict set of options, and are extremely useful for handling exhaustiveness.&lt;/p&gt;

&lt;p&gt;An enum is a first-class type, meaning they can take on functions and features that apply specifically to the class type, such as computed properties and instance methods(more on the specifics of class, structs, and enums &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html#ID83"&gt;here&lt;/a&gt;). &lt;/p&gt;

&lt;p&gt;Enums are declared with the enum keyword, followed by a capitalized name, then a list of cases, which act as the possible enum options, inside. Cases can be listed on separate lines, each with the case keyword in front, or all on one line separated by commas. Let’s use an enum that lists possible types of pet available in a pet store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Animal {
    case cat
    case dog 
    case rabbit
    case hamster
    case snake
    case turtle
    case fish
    case bird
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Animal {
    case cat, dog, rabbit, hamster, snake, turtle, fish, bird
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Either format is acceptable, but longer case lists might be easier to read through listed out as case statements on separate lines, as opposed to on one line. &lt;/p&gt;

&lt;p&gt;To declare an value of an enum type you can assign it directly&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var thatKittyInTheWindow = Animal.cat
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or assign the type, then specify the case with dot syntax. Listing the specific enum again is unnecessary because we already know which one the value will use.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var thatKittyInTheWindow: Animal = .cat
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The specificity of the enumeration is one of its advantages, because the listed cases pair perfectly with a switch statement. A switch statement will ‘switch’ (essentially ‘choose an option’) based on which case is handed to it, then take the appropriate action you have coded in. &lt;/p&gt;

&lt;p&gt;All options have to be covered in the switch statement, because it is by definition exhaustive. An option must be present for every possible case. If an option is not specified, the compiler will complain. If you want some options to produce the same result, you can group them, or you can include a default statement, which will be used as a fallback if a case has been left out of the switch. Let’s see an example using sounds these animals might make.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;switch Animal {
case .cat:
    print(“Meow”)
case .dog: 
    print(“Woof”)
case .rabbit, .hamster:
    print(“Squeak”)
case .snake:
    print(“Hisss”)
case .bird:
    print(“Tweet”)
default:
    print(“…”)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the .turtle and .fish cases would trip the default statement, while the .rabbit and .hamster cases have been placed together and will result in the same print statement.&lt;/p&gt;

&lt;p&gt;An enum can also have raw values associated with each case. These raw values are basic types only, such as strings, characters, and number types like ints and doubles. You add a raw value to an enum by adding a colon then the type after the enum name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Animal: String {
    case cat
    case dog 
    case rabbit
    case hamster
    case snake
    case turtle
    case fish
    case bird
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we’ve assigned a raw string value to the enum. By default, this will produce a raw value for each case that is a string version of the case keyword. Accessing the raw value for Animal.cat, for example, will produce “cat”, so value below will be “cat”.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var thatKittyInTheWindow: Animal = .cat
let value = thatKittyInTheWindow.rawValue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Assigning an Int as a raw value will automatically assign an integer value to each case, based on zero indexing. This also works if you specify the index for the first case item - the rest will receive an index automatically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Animal: Int {
    case cat = 1
    case dog 
    case rabbit
    case hamster
    case snake
    case turtle
    case fish
    case bird
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, dog would have a raw value of 2, rabbit 3, and so on. You can, of course, always specify each raw value to be something particular too, rather than letting the compiler handle it automatically. Perhaps here we would assign pet shop prices to each animal via raw value, or give them names.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Animal: String {
    case cat = “Socks”
    case dog = “Buddy”
    case rabbit = “Thumper”
    // and so on
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As long as the raw value is one of the basic accepted types it can be assigned. Once set, however, the raw value for any enum case is always the same. The situation above would only be practical if the store had one of each type of pet, since if they had multiple, the same name would apply across for each dog, etc.&lt;/p&gt;

&lt;p&gt;This problem can be remedied with associated values, however. An associated value is ‘associated’ with an enum case, but is specified only as a type. The actual value is set upon declaring a type of that enum case. This way, we can associate a string with each animal, which will be its name, but we will not have to assign a name upon declaration of the enum (like with raw values).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Animal {
    case cat(String)
    case dog(String) 
    case rabbit(String) 
    case hamster(String) 
    case snake(String) 
    case turtle(String) 
    case fish(String) 
    case bird(String) 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can ensure a given animal has a proper name, set separately when we declare a value of the Animal type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let thatKittyInTheWindow: Animal = .cat(“Tiger”)
let thatPuppyInTheWindow: Animal = .dog(“Lily”)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These associated values can then be used in a switch statement as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;switch Animal {
    case .cat(let name):
    print(“Kitty’s name is \(name)”)
    case .dog(let name):
    print(“Doggie’s name is \(name)”)
    // and so on
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we assign the associated value to constant, then use string &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292"&gt;interpolation&lt;/a&gt; to add it to a print statement. &lt;/p&gt;

&lt;p&gt;As you can see, there are a lot of possibilities for ways to use enums to your advantage, especially by pairing them with switch statements for exhaustive and easy to read code. There are even more uses out there - this short lesson only covered the basics, but the docs contain even more specific details if you want to delve into &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html"&gt;more&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>swift</category>
      <category>iosdevelopment</category>
      <category>enumerations</category>
    </item>
    <item>
      <title>Delegates in Swift</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Mon, 12 Oct 2020 20:31:36 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/delegates-in-swift-2kfa</link>
      <guid>https://forem.com/kduncanwelke/delegates-in-swift-2kfa</guid>
      <description>&lt;p&gt;The &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID276"&gt;delegate pattern&lt;/a&gt; is a very useful design solution in Swift - its handiness comes from the fact that it can pass responsibility around within your code. One class or struct can call a delegate method, and some other object takes care of doing the work, so it seems that it’s happening “behind the scenes”. &lt;/p&gt;

&lt;p&gt;Delegation can seem hairy and overly complicated at the outset, but if you break it down to its essentials, the pattern is pretty straightforward, and after employing it a few times, it will seem second nature.&lt;/p&gt;

&lt;p&gt;At the heart of the delegate pattern are protocols. A protocol itself is not a piece of code that does work; instead it acts as a blueprint that defines a set of requirements. These requirements can be functions, properties, and more that must be defined in the conforming object, so it can successfully obey the protocol.&lt;/p&gt;

&lt;p&gt;A &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID268"&gt;protocol&lt;/a&gt; is defined with the protocol keyword and a name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol MyProtocol {
    // the protocol requirements are defined inside
    var requiredString: String { get set }
    func requiredFunction() 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that the body of the function is not filled out, all that is defined is the name and any inputs. The string requirement here is declared with { get set } because, as a variable, it is gettable and settable. &lt;/p&gt;

&lt;p&gt;An object adopts the protocol by adding a colon after its name, then listing the protocol it wishes to adopt, and conforming to its requirements within.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct MyStruct: MyProtocol {
    // this object must then conform to protocol requirements
    var requiredString = “This is the conforming string”

    func requiredFunction() {
        print(“Here we have conformed to the function requirement with an implementation of the function”)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is all important to understand, because delegation relies on the implementation of a protocol. Together, a protocol and a delegate are what makes the delegate pattern happen. Let’s take a look at an example from my journaling app, &lt;a href="https://apps.apple.com/us/app/space-log/id1475375352?ls=1"&gt;Space Log&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--asO3glgF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1s4e3sf6w2dmx3vohhco.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--asO3glgF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1s4e3sf6w2dmx3vohhco.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;One of the features of Space Log is that it allows users to create to-do lists, and check off individual items. Here, delegation is used in the UITableViewCell file to detect when a cell’s button has been tapped, then calls the delegate’s method, which passes along info on the cell and its checked state to the detail view, where it then updates the appropriate checklist item’s completion value.&lt;/p&gt;

&lt;p&gt;Delegation allows this information to be communicated easily across the different objects involved. Let’s start with where the delegate protocol is declared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol CellCheckDelegate: class {
    func didChangeSelectedState(sender: CheckListTableViewCell, isChecked: Bool) 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the protocol requires a function, which has a cell and bool input. The protocol is class-bound, using the class keyword, which means the delegate, when declared, must be weak. Delegates should be declared as weak, so they are not held strongly in memory, in order to prevent a &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID51"&gt;strong reference cycle&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;Now we’ll see that declaration in action. The delegate is defined inside the CheckListTableViewCell file. It is weak, variable, and optional.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;weak var cellDelegate: CellCheckDelegate?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Below, inside the IBAction that handles taps on the cell button, is a call to the delegate’s function. Self, which is the cell, is passed in as the sender and a variable isChecked that is set based on the current checked or unchecked state is passed in as well. Note the use of self, as the delegate is declared within CheckListTableViewCell, and the question mark, since the delegate is an optional.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;self.cellDelegate?.didChangeSelectedState(sender: self, isChecked: isChecked)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This call then tells the detail controller, which conforms to the protocol, to take action. Let’s look at where this code is set forth. &lt;/p&gt;

&lt;p&gt;First, within func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) the cell’s delegate is set, after the cell has been declared, and before the cell is returned.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cell.cellDelegate = self
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates the bridge, so to speak, between CheckListTableViewCell and the cell that is created in the tableView, by referring to the delegate within CheckListTableViewCell (this 'holding onto each other' is why the delegate being declared as weak is important, since elements of code 'holding on' to each other is what can create a strong reference cycle if the weak keyword is not used).&lt;/p&gt;

&lt;p&gt;In an extension, the detail controller then adopts the CellCheckDelegate, and conforms to it by filling out implementation for the didChangeSelectedState function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension DetailViewController: CellCheckDelegate {

    func didChangeSelectedState(sender: CheckListTableViewCell, isChecked: Bool) {
    let path = self.tableView.indexPath(for: sender)
        if let selected = path {
        checkList[selected.row].isComplete = isChecked
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function is what ends up being performed when the delegate function is called from the IBAction within CheckListTableViewCell. It uses the sender (cell) path to find which checkList item needs to be modified, then assigns the completion value to the checkList item’s isComplete value. &lt;/p&gt;

&lt;p&gt;You can see this code in action in the repo &lt;a href="https://github.com/kduncanwelke/Space-Log"&gt;here!&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Employing the delegate pattern allows this process to be carried out in relatively few lines of code, and does so in a lightweight manner. I hope this has helped you understand delegates a bit better - if it has, give it a like! 💖&lt;/p&gt;

</description>
      <category>swift</category>
      <category>iosdevelopment</category>
      <category>delegates</category>
    </item>
    <item>
      <title>Optionals in Swift</title>
      <dc:creator>Kate</dc:creator>
      <pubDate>Mon, 12 Oct 2020 20:14:41 +0000</pubDate>
      <link>https://forem.com/kduncanwelke/optionals-in-swift-342h</link>
      <guid>https://forem.com/kduncanwelke/optionals-in-swift-342h</guid>
      <description>&lt;p&gt;When I first started learning Swift, I frequently referred to the documentation, but I also visited blogs run by other developers as well. Reading someone else’s explanation of a complex topic often helped my understanding. Now having published to the App Store, it’s time to pass the kindness along, and help other beginner developers get started. 😊&lt;/p&gt;

&lt;p&gt;Optionals were a confusing topic early on for me when I was learning Swift, so I will start there.&lt;/p&gt;

&lt;h3&gt;
  
  
  Optionals
&lt;/h3&gt;

&lt;p&gt;An &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID330"&gt;optional&lt;/a&gt;, at its simplest, is either something, or nothing at all. You can pick out an optional easily because each one is declared with a question mark at the end, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var optionalString: String?  
var optionalNumber: Int?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The value is either of the type listed before the question mark (the something), or it is nil (nothing). Optionals do not exist in Objective-C, but nil does, although it has a different meaning (see the docs for more on this). All you need to know for Swift, however, is that nil represents the absence of a value.&lt;/p&gt;

&lt;p&gt;You might be wondering why this is a good thing. Why do we want a value to possibly be nothing? What use is nothingness? A good deal of use, surprisingly. &lt;/p&gt;

&lt;p&gt;Imagine you have an app, like the Reminders app on your phone. You can enter text for a reminder, and you have the option to set a date for your reminder too. You might want some reminders that have dates, like appointments, and some that don’t, like a chore that isn’t time sensitive. Perhaps you revisit an entry later and assign a date, or decide that a date you added wasn’t necessary, and delete it.&lt;/p&gt;

&lt;p&gt;In this situation, a date for any reminder might exist, or it might not . . . sound familiar? Either is has a value, or none at all. That date would be the perfect place to use an optional.&lt;/p&gt;

&lt;p&gt;The fact that an optional can be nothing means that it has to be handled carefully, however. If you try to use an optional in a situation where your code expects a value, and the optional happens to be nil, you will get a runtime error (crash). &lt;/p&gt;

&lt;p&gt;This error will usually occur when you try to force unwrap an optional. Force unwrapping is done by adding an exclamation point to the end of an optional value like so:&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;Think of an optional like a present. You must unwrap it to see what’s inside. This implicit unwrapping will open up the optional, but it does so without checking that there is a valid value inside first. If you open it unexpectedly and what’s inside is nil, the present will ‘explode’ and throw a runtime error, causing a crash. It’s best always to open optionals carefully.  &lt;/p&gt;

&lt;p&gt;Luckily there are a couple of ways to safely unwrap the value, and avoid any exploding gifts. &lt;/p&gt;

&lt;p&gt;The first method involves a simple test for nil, followed by a force unwrap. In this case the force unwrap is safe, because we already carefully checked for nil using the ‘not equal’ operator. I would not recommend this as the best method, because these force unwraps are undesirable, but you may see it used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if optionalString != nil {
    print(“optionalString! is safe to force unwrap because we checked for nil”)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second method is called optional binding. This ‘binds’ the optional to a temporary value. If the optional contains something you can use the temporary value. If the optional is nil, there will be no value assigned and the statement will not be executed. If an else statement is included, this will be executed instead.&lt;/p&gt;

&lt;p&gt;Optional binding is commonly achieved through an if let or a guard let. An if let statement, below, exits later and has a limited scope (aka the variable only works inside of it):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if let myString = optionalString {
    print(“here’s myString”)
} else {
    print(“the optional string was nil)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A guard let statement, below, exits earlier if the value is nil (at the return), and has a larger scope, because the variable can be used safely after the statement.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;guard let myString = optionalString else { 
    print(“the optional was nil”)
    return
}

print(“here’s myString, it can be used now”)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which binding method you use depends upon your scope requirement and preference. &lt;/p&gt;

&lt;p&gt;A third method to handle optionals is to use the nil-coalescing operator, which is represented by ??.  If the value on the left-hand side of the ?? is nil, the right-hand side value will be used instead. &lt;/p&gt;

&lt;p&gt;This is best used in a case where you wish to supply a default value if nil is present, rather than performing a different action if the value is missing. An example situation might be retrieving album art. If you cannot access an image (aka it is nil), you might supply a default image instead.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let image = albumArt ?? defaultImage
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If albumArt is nil, defaultImage will be assigned to image.&lt;/p&gt;

&lt;p&gt;To read even more about optionals, visit the documentation page for more: &lt;a href="https://developer.apple.com/documentation/swift/optional"&gt;link&lt;/a&gt;. And a fun fact you might pick out - an optional is secretly an enum under the hood!&lt;br&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1f40hOaE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/57jeso4334uuxv55gk4t.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1f40hOaE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/57jeso4334uuxv55gk4t.jpg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>swift</category>
      <category>iosdevelopment</category>
      <category>optionals</category>
    </item>
  </channel>
</rss>
