如何在结构中解开 swift 选项 [英] how to unwrap swift optionals within a struct
问题描述
我正在学习 swift 并找到了一个在结构中包含可选属性的示例.当我尝试为可选项设置一个值时,我发现它为零.
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)")
收益
purchase name is lampshade, purchase price is nil
如果我尝试 (purchase.price.USD),我会收到错误消息可选类型‘价格’的值?"必须解包以引用封装基类型价格"的成员美元"
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?
推荐答案
如果您没有为 Optional
赋值,则不能直接设置 Optional
的属性> 本身,由于可选链接,usd
的 setter 不会被调用.
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.
相反,您需要为 purchase.price
分配一个 Price
.
Instead, you need to assign a Price
to purchase.price
.
var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price(USD: 19.2)
或者如果你想分配一个空的"price
,那么可选的链接就可以工作,因为现在price
不是nil
.
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
此外,您应该尝试在默认情况下使属性不可变(let
),并且仅在初始化后确实需要更改属性时才使属性可变(var
).您还应该只向属性添加默认值,因为它们具有默认值是有意义的.例如,name
不应该有一个,而应该是不可变的,它的值在 init
中设置.
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)
这篇关于如何在结构中解开 swift 选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!