I found this post to convert a Int
into 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:
var purchase: Bool = true
let data = NSData(bytes: &purchase, length: sizeof(Bool))
In my case I always know that the Bool
will be true. Since this is the case, I was wondering if there is a simpler method to convert the value "true" to a NSData
object.
Some background context:
I am storing this NSData
value in the keychain with this library .
I am also going to be convert the NSData
value back into a bool with NSKeyedUnarchiver.unarchiveObjectWithData
Swift 4 Solution
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
we can easily achieve this using JSONEncoder
cause Bool
struct
confirms Codable
Typealias
let mBoolValue = true
let boolData = try! JSONEncoder().encode(mBoolValue)
You can try extending Bool with a function that returns NSData
(I don't have my IDE with me right now, so the syntax might not be right)
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.