protocol definition question

I have the following:

public protocol RawBits: CustomStringConvertible, Collection {

    associatedtype RawValue

    var rawValue: RawValue { get set }

}

extension RawBits where RawValue: FixedWidthInteger, RawValue:
UnsignedInteger {

    [...fields and methods are defined here...]

}

struct RawBits8: RawBits {

    var rawValue: UInt8

}

This all works fine.

Now I want to be able to define an extension to which the following would
conform:

struct RawBitsX: RawBits {

    var rawValue: [UInt8]

}

rawValue is now an array rather than a simple type. I can't for the life of
me figure out how to indicate this in the 'where' clause of an extension to
RawBits. Can this be done? How?

Thanks for any assistance,

Frank

If you want to match [UInt8] specifically, just use the non-sugared definition:

extension RawBits where RawValue == Array<UInt8> {

}

If you want it to match any array, that’s more complicated. As far as I’ve been able to work out, you have to wrap it in a protocol. Most of Array’s usefulness comes from protocols anyway, so you can probably use Sequence, Collection, or one or more of the more specific Mutable/RandomAccess/RangeReplaceableCollection protocols.

extension RawBits where RawValue: Collection {

}

If you really need an array specifically, as far as I can tell you have to use a pattern I’ve used for a similar purpose with optionals:

protocol Arrayable {
    associatedtype T
    func asArray() -> [T]
}

extension Array: Arrayable {
    func asArray() -> [Element] {
        return self
    }
}

extension RawBits where RawValue: Arrayable {
    func foo() {
        let ary = rawValue.asArray()
        // ary is now an Array.
    }
}

It’s rather unfortunate this requires a somewhat ugly workaround, but, well, it’s not the worst or most commonly encountered of the shortcomings in the type system.

···

On Dec 13, 2017, at 9:42 PM, Frank Swarbrick via swift-users <swift-users@swift.org> wrote:

I have the following:

public protocol RawBits: CustomStringConvertible, Collection {
    associatedtype RawValue
    var rawValue: RawValue { get set }
}

extension RawBits where RawValue: FixedWidthInteger, RawValue: UnsignedInteger {
    [...fields and methods are defined here...]
}

struct RawBits8: RawBits {
    var rawValue: UInt8
}

This all works fine.
Now I want to be able to define an extension to which the following would conform:

struct RawBitsX: RawBits {
    var rawValue: [UInt8]
}

rawValue is now an array rather than a simple type. I can't for the life of me figure out how to indicate this in the 'where' clause of an extension to RawBits. Can this be done? How?

Thanks for any assistance,
Frank
_______________________________________________
swift-users mailing list
swift-users@swift.org <mailto:swift-users@swift.org>
https://lists.swift.org/mailman/listinfo/swift-users