问题描述
我有以下代码:
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?
,我发现这很奇怪,因为它是隐式展开的.
During runtime, product.price
is of type Price?
I find this weird since it's implicitly unwrapped.
我尝试给Price
一个init()
方法,结果相同.我也尝试在Product
定义中使用var price: Price! = Price(value: 0, currency: "CAD")
,结果相同. (我向Price
添加了一个成员初始化器.)
I've tried giving Price
an init()
method, with the same results. I've also tried using var price: Price! = Price(value: 0, currency: "CAD")
in the Product
definition, with the same results. (I add a memberwise initializer to Price
.)
这是怎么回事?
推荐答案
否,您明确将其设置为可选:
No, you explicitly set it to be optional:
struct Product {
var image: URL! // <-- Explicitly marked as optional via '!'
}
如果您希望它不是可选的,请不要通过!
或?
将其标记为可选:
if you want it to be non-optional, do not mark it as optional via !
or ?
:
struct Product {
var image: URL // <-- not marked as optional
}
!
和?
都是可选的.唯一的区别是,后者需要显式展开(if let
),而前者需要自动展开(如果使用不正确,可能会导致崩溃).
Both !
and ?
are optionals. The only difference being that the latter needs to be explicitly unwrapped (if let
) while the former is automatically unwrapped (potentially leading to crashes if used incorrectly).
这篇关于Swift嵌套的非可选结构提供了可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!