gpt4 book ai didi

swift - Swift 类初始值设定项中的可选类初始值设定项参数

转载 作者:行者123 更新时间:2023-11-28 13:33:40 24 4
gpt4 key购买 nike

我有一个名为 User 的类 init,类 User 包含一些参数。现在在 Offer 类中,您可以看到我将 User 类作为参数传递,但我想将其作为可选的。有没有办法在你的参数中有一个可选类?谢谢

struct User {
let uid: String
let username: String

init(uid: String, dictionary: [String: Any]) {
self.uid = uid
self.username = dictionary["username"] as? String ?? ""
}
}

struct Offer {
let user: User
let caption: String
let imageURL: String
let creationDate: Date

init(user: User, dictionary: [String: Any]) {
self.user = user
self.caption = dictionary["caption"] as? String ?? ""
self.imageURL = dictionary["image_url"] as? String ?? ""

let secondsFrom1970 = dictionary["creation_date"] as? Double ?? 0
self.creationDate = Date(timeIntervalSince1970: secondsFrom1970)
}
}

最佳答案

您的代码混淆了两个截然不同的事情:使用一组成员值初始化对象,以及从字典中提取这些成员。只需编写两个单独的初始值设定项:

import Foundation

struct User {
let uid: String
let username: String

/*
// Due to the absence of an explicit initializer declaration,
// the compiler will synthesize an implicit member-wise initailizer like this:
init(uid: String, username: String) {
self.uid = uid
self.username = username
}
*/
}

extension User {
// Putting this initializer in an extension preserves he member-wise intializer
init?(fromDict dict: [String: Any]) {
guard let uid = dict["uid"] as? String,
let username = dict["username"] as? String
else { return nil }

self.init(uid: uid, username: username)
}
}

struct Offer {
let user: User
let caption: String
let imageURL: String
let creationDate: Date

/*
// Due to the absence of an explicit initializer declaration,
// the compiler will synthesize an implicit member-wise initailizer like this:
init(
user: User,
caption: String,
imageURL: String,
creationDate: Date
) {
self.user = user
self.caption = caption
self.imageURL = imageURL
self.creationDate = creationDate
}
*/
}

extension Offer {
// Putting this initializer in an extension preserves he member-wise intializer
init?(fromDict dict: [String: Any]) {
guard let user = dict["user"] as? User,
let caption = dict["caption"] as? String,
let imageURL = dict["image_url"] as? String,
let secondsFrom1970 = dict["creation_date"] as? Double
else { return nil }

self.init(
user: user,
caption: caption,
imageURL: imageURL,
creationDate: Date(timeIntervalSince1970: secondsFrom1970)
)
}
}

一些注意事项:

  1. nil 的情况下使用 nil 合并运算符 (??) 提供无意义的默认值是非常糟糕的做法。它隐藏故障并默默地引入数据完整性问题;不要这样做。
  2. String 不是名为 imageURL 的成员的合适类型。使用 URL
  3. 如果这些指令来自 JSON,请使用 Codable 协议(protocol)来自动化所有这些样板代码。
  4. String 对于 ID 来说是一个糟糕的类型,主要是因为与更合适的类型如 UUID 相比,它真的很慢>整数。在大多数数据库中尤其如此,其中文本比较比 Int/UUID 比较慢很多

关于swift - Swift 类初始值设定项中的可选类初始值设定项参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56981765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com