在 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/