Swift嵌套的非可选结构提供了可选 [英] Swift nested non-optional structure gives optional

查看:110
本文介绍了Swift嵌套的非可选结构提供了可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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.)

这是怎么回事?

推荐答案

在运行时,product.price的类型为Price?我发现这很奇怪,因为它被明确设置为非可选

During runtime, product.price is of type Price? I find this weird since it's explicitly set to be non-optional

否,您明确将其设置为可选:

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嵌套的非可选结构提供了可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆