Mavro
Mavro

Reputation: 571

How to convert UInt8 to Bool in Swift 2

I'm having to redo all my code where I was using Boolean that worked in Swift 1.2. Now in Swift 2.0, I'm using Bool correctly, but I'm unclear how I can convert a UInt8 (0/1) into a Swift Bool.

Example:

 let timeDateValid:Bool = bytes[0]

Error Message: Cannot Convert Type 'UInt8' to specified type 'Bool'

Thanks!

Upvotes: 0

Views: 3025

Answers (3)

Can be optimized with

extension UInt8 {
    func toBool() -> Bool {
        switch self {
        case 0x01:
            return true
        default:
            return false
        }
    }
}

or to avoid switch

extension UInt8 {
    var toBool: Bool {
        return self == 0x01 ? true : false
    }
}

Upvotes: 1

dimohamdy
dimohamdy

Reputation: 3053

Swift3

Convert UInt8 Byte to Bool

extension UInt8 {
    func toBool() -> Bool {
        switch self {
        case 0x01:
            return true
        case 0x00:
            return false
        default:
            return false
        }
    }
}

Upvotes: 2

NobodyNada
NobodyNada

Reputation: 7634

Just test if it is 0:

let timeDateValid:Bool = (bytes[0] != 0)

Upvotes: 5

Related Questions