Help with Optionals in Structs

Hello, all. First post here. I am a rank beginner at Swift, so please pardon the (probably) simplistic question. I have begun working through the SwiftUI for Masterminds book (3rd Ed.) and am stumped about something. In the introduction to structs, they offer the following example (Listing 3-31, pg. 44):

struct Price {
     var USD = 0.0
     var CAD = 0.0
}
struct Item {
     var name: String = "Not defined"
     var price: Price?
}
var purchase = Item()
purchase.name = "Lamps"
purchase.price?.USD = 10.50

I am confused on a couple points. First, in the results window, it shows that the value after the last assignment statement is still nil rather than 10.50. Secondly, when I tried to print this value with the command print(purchase.price!.USD), I get an execution error: " Fatal error: Unexpectedly found nil while unwrapping an Optional value". So it appears the assignment is not working? If I don't reference one struct from another and just combine the members in one struct, I can get it to work as I think it should, so seems to have something to do with the dot notation between the two? I don't know.... any help appreciated. :slight_smile:

If you break your code down into smaller pieces, the last bit ends up being this:

Before:

purchase.price?.USD = 10.50

After:

var price = purchase.price
if price != nil { //this bit is what the ? does
  price!.USD = 10.50
}
purchase.price = price

Hopefully it's clearer in the expanded version why it would remain nil? Somewhere in your code you'll need to actually make a Price value using Price(…).

1 Like

Ok, very interesting. Thanks so much for your reply and breaking it down that way. I think I get the gist of what you are saying. I am just trying to follow the book's examples and understand what's taking place. You mentioned making a Price value using Price somewhere in the code. Not sure I know how or where to do that at this early stage of my learning. Can you tell me what that reference would look like? Thanks again, David.

You see this bit in the code you already have? That’s how you make an Item. You need to make a Price the same way.