ios - How to convert bool to NSData -


i found this post convert int nsdata

it says this:

var foo: int = 1000 let data = nsdata(bytes: &foo, length: sizeof(int)) 

i wondering, should same think converting bool nsdata, this:

 var purchase: bool = true  let data = nsdata(bytes: &purchase, length: sizeof(bool)) 

in case know bool true. since case, wondering if there simpler method convert value "true" nsdata object.

some background context:

i storing nsdata value in keychain this library.

i going convert nsdata value bool nskeyedunarchiver.unarchiveobjectwithdata

you can try extending bool function returns nsdata

(i don't have ide me right now, syntax might not right)

extension bool {   func tonsdata() -> nsdata {     var data: nsdata?     if ( self.value ) { //not sure if right syntax       return nsdata(bytes: 1, length: sizeof(int))     }     return nsdata(bytes: 0, lentgh: sizeof(int))   } } 

then bool have nsdata representation so

let b: bool = true let data: nsdata = b.tonsdata() 

i'm still new @ this, think above part of "protocol oriented programming" apple encourages.


Comments