问题
I'm learning swift and found an example that contains an optional property within a struct. When I try to set a value to the optional I find that it is nil.
struct Price{
var USD: Double = 0.0
var CAD: Double = 0.0
}
struct Item{
var name: String = "not defined"
var price: Price?
}
var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price?.USD = 19.2
print("purchase name is \(purchase.name), purchase price is \(purchase.price?.USD)")
yields
purchase name is lampshade, purchase price is nil
if I try (purchase.price.USD) I get an error "Value of optional type 'Price?' must be unwrapped to refer to member 'USD' of wrapped base type 'Price'
How can I unwrap price in order to set a value of USD?
回答1:
You cannot directly set a property of an Optional if you haven't assigned a value to the Optional itself, since due to the optional chaining, the setter of usd won't be called.
Instead, you need to assign a Price to purchase.price.
var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price(USD: 19.2)
Or if you want to assign an "empty" price, then optional chaining on that works, since now price is not nil.
var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price()
purchase.price?.USD = 19.2
Also, you should try to make properties immutable immutable (let) by default and only make properties mutable (var) if they really need to change after initialisation. You should also only add default values to properties where it makes sense for them to have a default value. For instance, name shouldn't have one, but rather, should be immutable with its value being set in the init.
struct Item{
let name: String
var price: Price?
}
var purchase = Item(name: "lampshade")
purchase.price = Price(USD: 19.2)
来源:https://stackoverflow.com/questions/62066240/how-to-unwrap-swift-optionals-within-a-struct