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

Jens Alfke jens at mooseyard.com
Tue Aug 30 18:15:56 CDT 2016


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 <http://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 <http://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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160830/78bb5252/attachment.html>


More information about the swift-users mailing list