Swift 3:使用NSCoder解码值的安全方法? [英] Swift 3: Safe way to decode values with NSCoder?

查看:218
本文介绍了Swift 3:使用NSCoder解码值的安全方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 3之前,您可以使用NSCoder解码布尔值,如下所示:

Before Swift 3, you decode boolean values with NSCoder like this:

if let value = aDecoder.decodeObjectForKey(TestKey) as? Bool {
   test = value
}

Swift 3中建议的方法是改用此方法:

The suggested approach in Swift 3 is to use this instead:

aDecoder.decodeBool(forKey: TestKey)

但是decodeBool的类引用没有说明如果您要解码的值实际上不是布尔值,则如何处理这种情况.您不能将decodeBool嵌入let语句中,因为返回值不是可选的.

But the class reference for decodeBool doesn't explain how to handle the situation if the value you're decoding isn't actually a boolean. You can't embed decodeBool in a let statement because the return value isn't an optional.

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

How do you safely decode values in Swift 3?

推荐答案

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

Took me a long time to figure out but you can still decode values like this. The problem I had with swift3 is the renaming of the encoding methods:

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

// swift3:
coder.encode(Any?, forKey: String)
coder.encode(Bool, forKey: String)

因此,当您使用coder.encode(boolenValue, forKey: "myBool")编码布尔值时,必须使用decodeBool对其进行解码,但是当您这样编码时:

So when you encode a boolean with coder.encode(boolenValue, forKey: "myBool") you have to decode it with decodeBool but when you encode it like this:

let booleanValue = true
coder.encode(booleanValue as Any, forKey: "myBool")

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

you can still decode it like this:

if let value = coder.decodeObject(forKey: "myBool") as? Bool {
   test = value
}

这篇关于Swift 3:使用NSCoder解码值的安全方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆