Swift 嵌套的非可选结构给出了可选的

标签 swift struct option-type

我有以下代码:

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/

相关文章:

ios - UITableViewCell 在滚动时重绘

swift - 如何在 swift 中向数组添加 pop() 扩展?

c - 设置在结构数组中定义的 "string"数组等于某物

c - C 中未命名的结构/union 有什么好处?

c++ - 使用 std::optional<int> 是否与使用 int 一样有效?

arrays - 为什么在 Optional Array 上的映射不同于 non-optionalArray

ios - 如何使用 JSQMessageViewController 使发件人显示名称出现?

ios - 在某些情况下,UIScrollView 中的减速非常慢

c - 函数 typedef 和从 C 中的结构调用函数

java - 返回两个可选值的总和,如果至少有一个不存在,则返回 null