请考虑以下示例类:
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
类型,因为像{这样的方法{1}},decodeBool()
,decodeInteger()
等无法展开?