我找到了 this post将 Int
转换为 NSData
它说要这样做:
var foo: Int = 1000
let data = NSData(bytes: &foo, length: sizeof(Int))
我在想,我是否应该像这样将 Bool
转换为 NSData
,像这样:
var purchase: Bool = true
let data = NSData(bytes: &purchase, length: sizeof(Bool))
在我的例子中,我总是知道 Bool
为真。既然如此,我想知道是否有更简单的方法将值“true”转换为 NSData
对象。
一些背景语境:
我将此 NSData
值存储在带有 this library 的钥匙串(keychain)中.
我还将使用 NSKeyedUnarchiver.unarchiveObjectWithData
将 NSData
值转换回 bool 值
最佳答案
Swift >= 4 解
我们可以使用 JSONEncoder
轻松实现这一点,因为 Bool
struct
确认 Codable
Typealias
let mBoolValue = true
let boolData = try! JSONEncoder().encode(mBoolValue)
关于ios - 如何将 bool 转换为 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509951/