Ошибка NSCoding во время необязательного назначения свойства

Рассмотрим следующий пример класса:

class C: NSObject, NSCoding {

    var b: Bool? // optional parameter

    // designated initializer
    init (b: Bool){...}

    // initializer by NSCoding protocol
    required init?(coder aDecoder: NSCoder) {
        // Lets assume the Bool parameter 'b' comes as NSObject. 
        // We should: (a) cast it to the type Bool and, 
        // (b) unwrap the value because parameter is optional 
        let _b: Bool = (aDecoder.decodeObject(forKey: keys.bool) as? Bool)! // SUCCESS

        // But by the reference manual, for the parameter of a Bool type
        // we should apply a decodeBool() method of a NSCoder class
        let _a: Bool = aDecoder.decodeBool(forKey: keys.amount) //RUNTIME ERROR
        // We've got 'Tread 1: signal SIGABRT' error 
        // at the NSKeyedUnarchiver.unarchiveObject(...) call

        // Lets try unwrap the value because the parameter 'b' is optional
        let _b: Bool = (aDecoder.decodeBool(forKey: keys.bool))! //ERROR
        // We've got compilation error 'Cannot force unwrap value 
        // non-optional type 'Bool'

        self.b = _b
        super.init()
    }

    // initializer by NSObject protocol
    override convenience init () {...}
    // method by NSCoding protocol
    func encode(with aCoder: NSCoder) {...}  
}

Вопрос в том:

Означает ли это, что я должен рассматривать типы Boolean, Integer, Float и т. д. как общий тип Object в случае необязательных параметров из-за невозможности развернуть такие методы, как decodeBool(), decodeInteger(), decodeFloat() и т. д.?


person Ruben Kazumov    schedule 06.06.2018    source источник
comment
stackoverflow.com/a/36154762/1305067 отвечает на ваш вопрос?   -  person paulvs    schedule 06.06.2018
comment
Спасибо @paulvs!   -  person Ruben Kazumov    schedule 06.06.2018