[swift-users] Trouble constraining a generic type in an extension

Jens Alfke jens at mooseyard.com
Tue Apr 12 11:11:36 CDT 2016


I’ve got a simple generic struct that wraps an instance of its parameter type.

public struct check<T> {
    let actual: T
    public init(_ a: T) {actual = a}
    ...

Now I want to add a method that only works with a specific type, Bool:
    public func isTrue()    {XCTAssertTrue(actual)}

As I’d expect, the compiler doesn’t allow this: “Cannot convert value of type ’T’ to expected argument type ‘Bool’”.
So I’m trying to put this method in an extension that constrains T:

public extension check<Bool> {
    public func isTrue()    {XCTAssertTrue(actual)}
}

This fails with "Constrained extension must be declared on the unspecialized generic type 'check' with constraints specified by a 'where’ clause”. OK, so I add a ‘where’ clause:

public extension check where T: Bool {
    public func isTrue()    {XCTAssertTrue(actual)}
}

This produces the error "type 'T' constrained to non-protocol type ‘Bool’”. This confuses me — why is constraining to a non-protocol type an error? The Swift Programming Language says “the ‘where’ clause … can express the constraints that a generic type T inherits from a class C”.

—Jens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160412/6921f359/attachment.html>


More information about the swift-users mailing list