how to unwrap swift optionals within a struct

大兔子大兔子 提交于 2021-02-05 09:24:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!