Swift 3:使用NSCoder解码值的安全方法?

Cra*_*lot 8 swift swift3

在Swift 3之前,你用NSCoder解码布尔值,如下所示:

if let value = aDecoder.decodeObjectForKey(TestKey) as? Bool {
   test = value
}
Run Code Online (Sandbox Code Playgroud)

Swift 3中建议的方法是使用它:

aDecoder.decodeBool(forKey: TestKey)
Run Code Online (Sandbox Code Playgroud)

但是类引用decodeBool并没有解释如果你正在解码的值实际上不是布尔值,如何处理这种情况.您不能嵌入decodeBoollet语句,因为返回值不是可选的.

你如何安全地解码Swift 3中的值?

err*_*sto 9

花了很长时间才弄清楚,但你仍然可以解码这样的值.我使用swift3的问题是重命名编码方法:

// swift2:
coder.encodeObject(Any?, forKey:String)
coder.encodeBool(Bool, forKey:String)

// swift3:
coder.encode(Any?, forKey: String)
coder.encode(Bool, forKey: String)
Run Code Online (Sandbox Code Playgroud)

因此,当你编码一个布尔值时,coder.encode(boolenValue, forKey: "myBool")你必须用它来解码它,decodeBool但是当你对它进行编码时:

let booleanValue = true
coder.encode(booleanValue as Any, forKey: "myBool")
Run Code Online (Sandbox Code Playgroud)

你仍然可以像这样解码它:

if let value = coder.decodeObject(forKey: "myBool") as? Bool {
   test = value
}
Run Code Online (Sandbox Code Playgroud)


ped*_*uan 6

当想要使用建议的decodeBool时,这是安全的(对于使用nil-coalescing op.的更短代码).

let value = aDecoder.decodeObject(forKey: TestKey) as? Bool ?? aDecoder.decodeBool(forKey: TestKey)
Run Code Online (Sandbox Code Playgroud)

在确定它是Bool,IMO的情况下,可以使用decodeBool.