[英]How to convert bool to NSData
I found this post to convert a Int
into NSData
我发现这篇文章将
Int
转换为NSData
It says to do this:它说要这样做:
var foo: Int = 1000
let data = NSData(bytes: &foo, length: sizeof(Int))
I was wondering, should I do the same think for converting a Bool
to NSData
, like this:我想知道,我是否应该像这样将
Bool
转换为NSData
:
var purchase: Bool = true
let data = NSData(bytes: &purchase, length: sizeof(Bool))
In my case I always know that the Bool
will be true.就我而言,我总是知道
Bool
将是真的。 Since this is the case, I was wondering if there is a simpler method to convert the value "true" to a NSData
object.既然是这种情况,我想知道是否有更简单的方法将值“true”转换为
NSData
对象。
Some background context:一些背景背景:
I am storing this NSData
value in the keychain with this library .我将此
NSData
值存储在此库的钥匙串中。
I am also going to be convert the NSData
value back into a bool with NSKeyedUnarchiver.unarchiveObjectWithData
我还将使用
NSKeyedUnarchiver.unarchiveObjectWithData
将NSData
值转换回 bool
Swift 4 Solution Swift 4 解决方案
if let isBool = value as? Bool
{
var valueInInt = Int(NSNumber(value: isBool)) //Convert Bool to Int
let data = Data(bytes: &valueInInt, count: MemoryLayout.size(ofValue: valueInInt) //Int to Data
}
Swift >= 4 Solution Swift >= 4 解决方案
we can easily achieve this using JSONEncoder
cause Bool
struct
confirms Codable
Typealias
我们可以使用
JSONEncoder
轻松实现这JSONEncoder
因为Bool
struct
确认了Codable
Typealias
let mBoolValue = true
let boolData = try! JSONEncoder().encode(mBoolValue)
You can try extending Bool with a function that returns NSData您可以尝试使用返回 NSData 的函数扩展 Bool
(I don't have my IDE with me right now, so the syntax might not be right) (我现在没有 IDE,所以语法可能不正确)
extension Bool {
func toNSData() -> NSData {
var data: NSData?
if ( self.value ) { //not sure if this is the right syntax
return NSData(bytes: 1, length: sizeof(Int))
}
return NSData(bytes: 0, lentgh: sizeOf(Int))
}
}
Then any bool will have NSData representation like so然后任何 bool 都会有像这样的 NSData 表示
let b: Bool = true
let data: NSData = b.toNSData()
I'm still new at this, but I think the above is part of "protocol oriented programming" that apple encourages.我对此还是个新手,但我认为上述内容是苹果鼓励的“面向协议编程”的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.