Reputation: 1435
I have a convenience initializer that calls onto an initializer that calls onto a super class initializer with header init!(data: Data!)
. What I don't understand is why I am getting the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value.
I have tried initializing a random Data
object with no data but I still obtain this error any ideas?
Code:
Convenience init(itemId: String) {
let d: Data = Data.init()
self.init(data: d) // error here!
}
required init!(data: Data?) {
super.init(data: data)
}
super class from obj c library:
-(id)initWithData:(NSData*)data {
if ([self init]) {
//some code
}
return nil
}
Upvotes: 0
Views: 303
Reputation: 6622
You're using implicitly unwrapped optional parameters and initializers. If you'd like to have a failable initializer, you should use init?
instead. As for passing in an argument that is implicitly unwrapped. That is really dangerous, too. Marking things as implicitly unwrapped is very convenient for avoiding the Swift compiler complaining, but it will often lead to this problem.
The problem is your call to super.init
is returning nil
.
This example shows you a safe way to do failable initialization.
// This is a stand in for what your super class is doing
// Though I can't tell you why it is returning nil
class ClassB {
required init?(data: Data?) {
return nil
}
}
class ClassA: ClassB {
convenience init?(itemId: String) {
let d: Data = Data.init()
self.init(data: d) // error here!
}
required init?(data: Data?) {
super.init(data: data)
}
}
if let myObject = ClassA.init(itemId: "ABC") {
// non-nil
} else {
// failable initializer failed
}
Upvotes: 2