我有以下代码:
struct Product {
var image: URL!
var title: String!
var price: Price!
var rating: Float!
var url: URL!
}
struct Price {
var value: Double!
var currency: String! // should be enum
}
我稍后初始化一个 Product
:
product = Product(
image: URL(string: "...")!,
title: "...",
price: Price(
value: 5.99,
currency: "CAD"
),
rating: 4.5,
url: URL(string: "...")!
)
在运行时,product.price
的类型是 Price?
我觉得这很奇怪,因为它是隐式解包的。
我试过给 Price
一个 init()
方法,结果相同。我也尝试过使用 var price: Price! = Price(value: 0, currency: "CAD")
在 Product
定义中,结果相同。 (我向 Price
添加了一个成员初始化器。)
这是怎么回事?
最佳答案
During runtime, product.price is of type Price? I find this weird since it's explicitly set to be non-optional
不,您明确将其设置为可选:
struct Product {
var image: URL! // <-- Explicitly marked as optional via '!'
}
如果您希望它是非可选的,请不要通过 !
或 ?
将其标记为可选:
struct Product {
var image: URL // <-- not marked as optional
}
!
和 ?
都是可选的。唯一的区别是后者需要显式解包(if let
),而前者是自动解包(如果使用不当可能导致崩溃)。
关于Swift 嵌套的非可选结构给出了可选的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103331/