我已对此进行了上下阅读,并在这里了解了基本知识-我只是不明白为什么会收到此错误。我使用第二个init从Firebase实例化一个客户,但是即使我注释掉其中的所有内容,我仍然会收到错误
Variable 'self.customerType' used before being initialized
在初始化声明?
class Customer {
enum customerTypes {
case consumer
case business
}
// MARK - properties
var id: String?
let customerType: customerTypes
var name1: String
var name2: String?
var address: Address?
var phone: String?
var email: String?
struct Address {
var street: String
var postalCode: String
var city: String
var country: String = "Norway"
}
init(type: customerTypes, name1: String, name2: String?, phone: String, email: String, address: Address? ) {
self.customerType = type
self.name1 = name1
self.name2 = name2
self.phone = phone
self.email = email
self.address = address
}
init?(data: [String: Any]) {
guard let type = data["customerType"] as? String else { return }
guard let name1 = data["name1"] as? String else { return }
self.customerType = type == "Consumer" ? .consumer : .business
self.name1 = name1
// if let name2 = data["name2"] as? String { self.name2 = name2 }
// if let phone = data["phone"] as? String { self.phone = phone }
// if let email = data["email"] as? String{ self.email = email }
// if let address = data["address"] as? [String: Any] {
// let street = address["street"] as? String
// let postCode = address["postCode"] as? String
// let city = address["city"] as? String
// if street != nil && postCode != nil && city != nil {
// self.address = Address(street: street!, postalCode: postCode!, city: city!)
// }
// }
}
我在这里忽略了什么简单的问题?
答案 0 :(得分:1)
您声明了一个初始化器,该初始化器承诺将返回初始化的const channel = client.channels.cache.get('<channelid>');
const person1 = client.users.cache.get('<userid>');
const person = client.users.cache.get('<userid>');
client.on('message', message =>{
client.on('presenceUpdate', () =>{
if(person1.user.presence.status === 'dnd' || person1.user.presence.status === 'online'){
channelforstatus.send('person1 is now online');
}
else if(peron1.user.presence.status === 'offline' || person1.user.presence.status === 'idle'){
channel.send('person1 is offline');
}
client.on('message', message => {
client.on('presenceUpdate', () =>{
if(person.user.presence.status === 'dnd' || person.user.presence.status === 'online'){
channel.send('person is now on');
}
else if(person.user.presence.status === 'offline' || person.user.presence.status === 'idle'){
channel.send('person is now off');
}
});
});
});
});
或不返回.send()
(因为它容易出错)。您还声明Customer
作为该类的属性之一。
这意味着,如果您成功从初始值设定项返回(也就是说,不返回Customer
),则必须将该属性初始化为某个值。
该错误对于错误的位置不是很有帮助,因为该错误实际上在下面的行中。只需将let customerType: customerTypes
放入nil
中,就表示您的对象已成功初始化,但尚未成功初始化,因为尚未将return
设置为值。
因此,如果将guard
放在customerType
子句中,您将说初始化失败,则无需在return nil
中输入值。
答案 1 :(得分:-1)
没有初始值的属性需要在init
内设置。您可以通过将其设置为Optional
或设置默认值来解决此问题:
init?(data: [String: Any]) {
customerType = .consumer
name1 = ""
}
或:
var customerType: customerTypes?
var name1: String?
注意:通过设置属性Optional
,编译器会假定初始值为nil
。