我为具有标题和内容属性的笔记创建了模型类。我在第二个init中收到一个错误,该错误是:从初始化返回而不初始化所有存储的属性。我感觉好像我缺少一些东西,我似乎看不到它。这是代码:
class Note{
private var _title: String
private var _content: String
var title: String!{
return self._title
}
var content: String!{
return self._content
}
init(title: String, content: String){
self._title = title
self._content = content
}
init(noteData: Dictionary<String, AnyObject>) {
if let title = noteData["title"] as? String {
self._title = title
}
if let content = noteData["content"] as? String {
self._content = content
}
}
}
答案 0 :(得分:2)
您必须在其初始化程序中初始化类的所有属性。关于字典初始化程序,应该使它容易出错,并在缺少键/值对的情况下返回nil:
class Note {
let title: String
let content: String
init(title: String, content: String) {
self.title = title
self.content = content
}
init?(dictionary: [String: Any]) {
guard
let title = dictionary["title"] as? String,
let content = dictionary["content"] as? String
else { return nil }
self.title = title
self.content = content
}
}
请注意,如果使用结构而不是类,您甚至不必为自定义对象实现初始化程序:
struct Note {
let title: String
let content: String
init?(dictionary: [String: Any]) {
guard
let title = dictionary["title"] as? String,
let content = dictionary["content"] as? String
else { return nil }
self.title = title
self.content = content
}
}
答案 1 :(得分:1)
问题在于,在第二次初始化中,如果展开失败,则不会设置属性。为了使初始化正常工作,所有非必需的属性都需要值。解决此问题的最佳方法是使属性成为可选。
可选属性:
private static final Object loggerParent = java.util.logging.Logger.getLogger("mycompany.package1");
private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(MyClass.class.getName());
通过使属性为可选,您可以避免在init中执行if let:
private var title: String?
private var content: String?
不过,在使用属性时,请务必安全地解开包装!