John Difool
John Difool

Reputation: 5732

Array of booleans extension

Using Swift 1.2, I am trying to extend the array class exclusively for the type Bool to return a bitset value in an Int. I can't get this to work after trying many ways:

extension Array {        
    func toUInt32<T: BooleanType>(Void) -> UInt32 {
        let numBits = self.count
        assert(numBits < 32)
        var result: UInt32 = 0
        for (idx, bit) in enumerate(self) {
            if bit {
                result |= UInt32(1 << (7 - (idx % 8)))
            }
        }
        return result
    }
}

It's unclear to me why the enumerate on Bool array in the bit variable can't be tested that way. I am also not sure how I can extend the array class for a single type (here it's using BooleanType.) What am I doing wrong?

Upvotes: 1

Views: 98

Answers (2)

John Difool
John Difool

Reputation: 5732

This now works in Swift 2.2:

extension Array where Element:BooleanType {
    func toUInt32() -> UInt32 {
        let numBits = self.count
        assert(numBits < 32)
        var result = UInt32(0)
        for (idx, bit) in self.enumerate() {
            if bit {
                result |= UInt32(1 << (7 - (idx % 8)))
            }
        }
        return result
    }
}

var bools: [Bool] = [true, true, false]
print(bools.toUInt32())

Upvotes: 0

Airspeed Velocity
Airspeed Velocity

Reputation: 40973

You cannot currently (Swift 1.2) extend an existing generic type with a method that imposes further constraints on that function’s generic type. So you can’t, in this example, write a method that requires the array to contain booleans.

Instead, you can write a free function that takes an array (or any collection) as a parameter, and then require that collection to contain bools:

func toUInt32<C: CollectionType where C.Generator.Element: BooleanType>(source: C) -> UInt32 {
    let numBits = count(source)
    assert(numBits < 32)
    var result: UInt32 = 0
    for (idx, bit) in enumerate(source) {
        if bit {
            // guessing you meant |= rather than != ?
            result |= UInt32(1 << (7 - (idx % 8)))
        }
    }
    return result
}

Upvotes: 2

Related Questions