从初始值设定项返回,而不初始化所有存储的属性Swift Xcode 10.0



我的结构中的所有变量都是可选的,那么在构造函数中我也会遇到这个问题吗?"从初始值设定项返回而不初始化所有存储的属性">

struct Conversation : Codable {

let chat_id : String?
let id : String?
let name : String?
let profile_pic : String?
let last_message_from : String?
let message : String?
let time : String?
let unread_count : String?
let member_count : String?
var type : ChatType = .Single
var doctors:[Doctors]?
enum CodingKeys: String, CodingKey {
case chat_id = "chat_id"
case id = "id"
case name = "name"
case profile_pic = "profile_pic"
case last_message_from = "last_message_from"
case message = "message"
case time = "time"
case unread_count = "unread_count"
case member_count = "member_count"
case doctors = "doctors"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
chat_id = try values.decodeIfPresent(String.self, forKey: .chat_id)
id = try values.decodeIfPresent(String.self, forKey: .id)
name = try values.decodeIfPresent(String.self, forKey: .name)
profile_pic = try values.decodeIfPresent(String.self, forKey: .profile_pic)
last_message_from = try values.decodeIfPresent(String.self, forKey: .last_message_from)
message = try values.decodeIfPresent(String.self, forKey: .message)
time = try values.decodeIfPresent(String.self, forKey: .time)
unread_count = try values.decodeIfPresent(String.self, forKey: .unread_count)
member_count = try values.decodeIfPresent(String.self, forKey: .member_count)
doctors = try values.decodeIfPresent([Doctors].self, forKey: .doctors)
}

init(doctor:Doctors) {
self.id = doctor.doctorId
self.profile_pic = doctor.doctorPic
self.type = .Single
}


}

如果您创建了一个初始值设定项,您需要为初始值设定器中所有存储的属性指定值,则不能使用属性的默认值。因此,即使您将属性声明为Optional,如果您希望它们为nil,也需要在初始值设定项中为它们分配nil值。

与您的问题无关,但如果您的所有属性名称都与JSON键匹配,则无需声明CodingKeys,也无需手动编写init(from:)初始值设定项,编译器可以在您的简单情况下自动为您合成。但是,您应该遵守Swift命名约定,这是变量名(包括enum大小写)的lowerCamelCase,因此相应地重命名您的属性,然后您将需要CodingKeys

请注意,你的很多类型实际上都没有意义。为什么这些变量被称为countStrings?如果它们以Strings的形式来自后端,请将它们转换为init(from:)中的Ints。此外,在init(doctor:)中,将doctor实际添加到doctors数组中是有意义的。

struct Conversation : Codable {
let chatId: String?
let id: String?
let name: String?
let profilePic: String?
let lastMessageFrom: String?
let message: String?
let time: String?
let unreadCount: String?
let memberCount: String?
var type: ChatType = .single
var doctors:[Doctors]?
enum CodingKeys: String, CodingKey {
case chatId = "chat_id"
case id
case name
case profilePic = "profile_pic"
case lastMessageFrom = "last_message_from"
case message
case time
case unreadCount = "unread_count"
case memberCount = "member_count"
case doctors
}
init(doctor:Doctors) {
self.id = doctor.doctorId
self.profilePic = doctor.doctorPic
self.type = .single
self.chatId = nil
self.name = nil
self.lastMessageFrom = nil
self.message = nil
self.time = nil
self.unreadCount = nil
self.memberCount = nil
self.doctors = [doctor]
}
}

最新更新