Search code examples
iosswiftnsdataoption-type

How to convert optional NSData to optional Bool


I have a NSData variable called: isMaxVersionEnabled? it is a optional.

I want to convert isMaxVersionEnabled to an optional Bool.

So far I have figured out how to convert a NSData value to a bool like this:

NSKeyedUnarchiver.unarchiveObjectWithData(<NSData value>)

but I am not sure how to utilize it because the input must be unwrapped and that is a problem since isMaxVersionEnabled might be nil.


Solution

  • You can get NSData Int value(very first bytes) and compare with 0 to get bool value

    var boolValue = false
    var value: Int = 0
    isMaxVersionEnabled?.getBytes(&value, length: sizeof(Int))
    if value != 0 {
        boolValue = true
    }
    
    print(boolValue)