我到处寻找,但找不到此代码无效的原因。我正在尝试初始化我的User类,它将与Firebase一起使用,因此我需要初始化字典以便能够检索JSON数据。我已经做了很多次这样的事情并且没有任何问题但是由于某种原因,这次xcode给了我"从初始化器返回而没有初始化所有存储的属性"。从我所看到的所有属性都被初始化。我错过了什么吗?提前谢谢您的支持!
enum UserAccessLevel: String {
case unknown = "Unknown"
case executiveProducer = "Executive Producer"
case topTierProducer = "Top Tier Producer"
case lowTierProducer = "Low Tier Producer"
case crew = "Crew Member"
case vendor = "Vendor"
case talent = "Talent"
}
enum Access: String {
case granted = "true"
case denied = "false"
}
enum FIRUserData: String {
case firstName = "firstName"
case lastName = "lastName"
case city = "city"
case state = "state"
case profileImage = "profileImage"
case userName = "userName"
case accessLevel = "accessLevel"
}
protocol User {
var firstName: String { get set }
var lastName: String { get set }
var city: String { get set }
var state: USAState { get set }
var profileImage: String { get set }
var userName: String { get set }
var accessLevel: UserAccessLevel { get set }
func createUser() throws
func signInUser() throws
func signOutUser()
func archiveProject()
func activateProject()
func deleteProject()
}
class UserType: User {
var firstName: String
var lastName: String
var city: String
var state: USAState
var profileImage: String
var userName: String
var accessLevel: UserAccessLevel
init(firstName: String, lastName: String, city: String, state: USAState, profileImage: String, u accessLevel: UserAccessLevel) {
self.firstName = firstName
self.lastName = lastName
self.city = city
self.state = state
self.profileImage = profileImage
self.userName = "\(firstName).\(lastName)"
self.accessLevel = accessLevel
}
init(userName: String, userData: Dictionary <String, Any>) {
self.userName = userName
if let firstName = userData[FIRUserData.firstName.rawValue] {
self.firstName = firstName as! String
}
if let lastName = userData[FIRUserData.lastName.rawValue] {
self.lastName = lastName as! String
}
if let city = userData[FIRUserData.city.rawValue] {
self.city = city as! String
}
if let state = userData[FIRUserData.state.rawValue] {
self.state = state as! USAState
}
if let profileImage = userData[FIRUserData.profileImage.rawValue] {
self.profileImage = profileImage as! String
}
if let accessLevel = userData[FIRUserData.accessLevel.rawValue] {
self.accessLevel = accessLevel as! UserAccessLevel
}
}
答案 0 :(得分:2)
在你的init
类的第二个UserType
中,Xcode并不认为保证设置所有类属性,因为if
语句可能会失败。
解决方案是为您的所有else
语句添加if
块:
init(userName: String, userData: Dictionary <String, Any>) {
self.userName = userName
if let firstName = userData[FIRUserData.firstName.rawValue] as? String {
self.firstName = firstName
} else {
firstName = //something else
}
//do the same thing with other if statements
}
答案 1 :(得分:0)
如果pickup_date_time_from = DateTimeField(input_formats=["%m/%d/%Y %I:%M %p"])
字典中缺少值,则第二个初始值设定项不会初始化字段。在这种情况下,您需要决定UserType的字段会发生什么。