Can we require StringProtocol.UTF8View be a BidirectionalCollection?

StringProtocol.UTF8View only requires Collection conformance, even though StringProtocol itself, as well as the UTF16View and UnicodeScalarView, are BidirectionalCollections. The actual UTF8Views for String and Substring are of course bidirectional. It's actually commented out from the protocol definition, which makes me think it may have been an oversight not to un-comment it?

This is just a really weird asymmetry which forces me to write a bunch of additional constraints. Given that StringProtocol is kind of "sealed", would it be possible to fix this? Or would it break ABI?

4 Likes

I recently came across this issue.

My (ugly & silly) workaround is like this:

private protocol _BidirectionalUTF8View: BidirectionalCollection,
                                         Sendable where Element == UTF8.CodeUnit,
                                                        Index == String.Index {}
extension String.UTF8View: _BidirectionalUTF8View {}
extension Substring.UTF8View: _BidirectionalUTF8View {}


private protocol _BidirectionalUTF8ViewAvailableStringProtocol: Sendable {
  associatedtype BidirectionalUTF8View: _BidirectionalUTF8View
  var utf8: BidirectionalUTF8View { get }
}
extension String: _BidirectionalUTF8ViewAvailableStringProtocol {}
extension Substring: _BidirectionalUTF8ViewAvailableStringProtocol {}

I also wonder why StringProtocol's UTF8View doesn't need to conform to BidirectionalCollection. :thinking: