super init with data error

时间:2017-07-14 21:09:13

标签: swift swift3 initialization

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
}

1 个答案:

答案 0 :(得分:2)

您正在使用implicitly unwrapped optional参数和初始值设定项。如果您想要一个可用的初始化程序,则应使用init?代替。至于传递一个隐含地展开的参数。这也很危险。将事物标记为隐式解包对于避免Swift编译器抱怨非常方便,但它通常会导致此问题。

问题是,您对super.init的回复正在返回nil

此示例显示了一种可安全的初始化方法。

// 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
}