Left cloud filled with code
A napping developer

Optionals in Swift, Part 3

Saturday, February 24, 2024 9:40 AM

This is a sample blog post

In order to explore optional chaining, let’s make our banking app more realistic. In an app like this, we’d probably use a struct (short for structure) to organize customer information. If you’re not familiar with structs, think of them as a template for structuring (organizing) data. In Swift, they are defined like this:

struct Customer {

  var firstNameString

  var lastNameString

  var checkingBalanceDouble

  var savingsBalanceDouble?

  let monthlyFee = 3.99

}

We’ve defined a struct called Customer and added some variables to it. These variables are placeholders that define what information is stored in the struct. Even though we recognize them as variables, in the context of a struct they’re referred to as “properties". So we’ve defined some properties that each customer will have. You’ll notice that we’ve made savingsBalance an optional double because we know that a specific customer may or may not have a savings account.  Because structs are just templates that define the data we want for each customer, we’re going to use the template to create one for each customer. 


We now have a structure that defines the things we want to know about each customer. This struct is just a template, it doesn’t actually hold any information except for a constant called monthlyFee. We’ve initialized monthlyFee because we know what its value is.. In order to use this struct, we have to create one for each actual customer. This is called “instantiation”, meaning “to create an instance of”. The jargon can be confusing, but it just means doing this:

var someCustomer = Customer(firstName"Tom"lastName"Tresh"checkingBalance0)

We’ve created an actual instance of a customer called someCustomer by using our Customer template, and we’ve given it some actual data about this specific person.  Notice that we don’t have to provide an initial value for savingsBalance because it’s an optional


Here’s how we might use this in our banking app:

•••

If you find any of these posts useful, please make a charitable donation

Link to the Epilepsy Foundation of Kentuckiana
Link to The Asclepius Initiative