[swift-users] How to extend a generic type with a Bool constraint?

Dan Loewenherz dan at lionheartsw.com
Wed Aug 31 12:21:03 CDT 2016

You'll need to specify a protocol where you're currently specifying "Bool".
A generic constraint can't take a concrete type as an argument. So you
could do this:

protocol BooleanType {}
extension Bool: BooleanType {}

extension foo where T: BooleanType {

If you don't like this, you can define a protocol with an associatedtype
and use a protocol extension to add this functionality to foo<T> instead.

protocol bar {
    associatedtype X

extension bar where X == Bool {

public struct foo<T>: bar {
    typealias X = T


On Tue, Aug 30, 2016 at 6:15 PM, Jens Alfke via swift-users <
swift-users at swift.org> wrote:

> I have a generic type, and I want to add some methods that are available
> when the type parameter is Bool. *(This is in Xcode 8 beta 6, btw.)*
> public struct foo<T> {
> ...
> }
> extension foo where T: Bool {
>> }
> The above fails to compile, with "type 'T' constrained to non-protocol
> type ‘Bool’”. Is that an error? The book doesn’t say that type constraints
> have to be to protocols; in fact the example in the section “Type
> Constraint Syntax” shows a type constraint that requires T to be a subclass
> of SomeClass.*
> OK, so I’ll find a protocol for “boolean-like” values that’s implemented
> by Bool. The Swift reference for `Bool` in Xcode doesn’t list anything.
> Swiftdoc.org shows a protocol `Boolean` that looks like exactly what I
> want, but my compiler’s never heard of it; is this something that snuck in
> post-3.0? If I switch Swiftdoc.org back to Swift 2.2, it shows an
> equivalent protocol called `BooleanType`, but if I try to use that, the
> compiler says "'BooleanType' has been renamed to ‘Bool’”.
> At this point I threw my laptop at the wall.
> Not really, but I started to miss the stability and simplicity of C++… :-p
> How the @$*% do I do this?
> —Jens
> * In fact the book never seems to talk about type constraints in generic
> type extensions. It covers each of the two concepts, but not how to use
> them together.
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160831/e1aafbdb/attachment.html>

More information about the swift-users mailing list