swift - 何时在 Swift 中使用可选类型背后的原则?

标签 swift oop option-type

在 Swift 中设计类/结构时,确定何时应使用 Optional 类型的最佳实践是什么?

例如,假设我正在将 JSON 响应映射到 Photo 对象,并且有一个属性 photographerName,它只是一个字符串。有时我们会在响应中收到字段 photographerName 的空字符串。

我的 Photo 对象是否应该使用 String? 类型并将其分配给 nil?或者使用 String 类型并将其设置为空字符串?

最佳答案

这实际上取决于您要在应用程序中使用的应用程序架构和数据结构。

没有规则可以描述如何在应用程序架构中正确使用可选链。

首先,我们应该知道什么是optional chaining .

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

根据我的经验,当我显然无法定义我的模型是否可以具有某些关系或属性时,我会在我的数据结构中使用可选值。

例子:

struct User {
    let name: String
    let email: String
    var friends: [String]?

    init(name: String, email: String) {
        self.name = name
        self.email = email
    }
}

let user = User(name: "Oleg", email: "Oleg@email.com")

我知道用户会有姓名和电子邮件,但我不知道他是否有任何 friend 。此外,通过这种方式,我可以防止我的代码对 nil 对象执行操作。

如果您描述它实际上取决于应用程序的体系结构和要求。例如,如果 photographerName 为空,我们是否应该显示占位符?是否有任何其他操作正在使用 photographerName 属性?

关于swift - 何时在 Swift 中使用可选类型背后的原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44505311/

相关文章:

swift - 从命令行读取输入时允许行编辑

java - 如何正确使用继承,避免向下转型

haskell - 结合仿函数和单子(monad)

java - 用 java 8 可选替换空检查

java - Android Studio 在使用 orElseThrow 方法时需要捕获 Throwable

ios - 返回数组的快速函数

ios - 使用 Swift 的 SKVideoNode 中的垂直视频方向问题

ios - UIAlertController 不会显示 - 在 Swift 中

php - 在结果集中实例化对象......最佳实践?

c++ - X() = delete; 构造函数的区别和私有(private) X();