Hello everyone!

My first mail on the list. That means I can't reply directly to the mail I found in the archive.

In addition to what Kevin already suggested here https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20171211/006743.html there is another more generic solution to circumvent the problem that you have to specify a concrete type for the array element.
You could use a second associated type in the protocol definition.

This is how it could look like:



protocol RawBits {
    associatedtype RawElement: FixedWidthInteger
    associatedtype RawValue = RawElement
    var rawValue: RawValue { get set }
}



extension RawBits where RawElement: UnsignedInteger, RawValue == Array<RawElement> {
    func testArray() {
        print("RawElement: \(RawElement.self) RawValue: \(RawValue.self)")
    }
}

extension RawBits where RawElement: UnsignedInteger, RawValue == RawElement {
    func testUnsigned() {
        print("RawElement: \(RawElement.self) RawValue: \(RawValue.self)")
    }
}



struct RBits<RawElement: FixedWidthInteger>: RawBits {
    var rawValue: RawValue
}

struct RBitsX<RawElement: FixedWidthInteger>: RawBits {
    var rawValue: [RawElement]
}



var rb = RBits(rawValue: 42 as UInt32)
rb.testUnsigned() // RawElement: UInt32 RawValue: UInt32

var rbx = RBitsX(rawValue: [1 as UInt8, 2, 3])
rbx.testArray() // RawElement: UInt8 RawValue: Array<UInt8>



_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to