Detecting if String is backed by utf-8 or utf-16

With the Swift 5 compiler changing String's native representation to be backed by UTF-8, code that wants to operate as fast as possible on String code units should naturally use UTF-8. However if the String is bridged from NSString then the backing representation will still be UTF-16.

Is there any supported way to detect if a given String is backed by UTF-8 or UTF-16, so I can pick the appropriate implementation?

I think the property you're looking for is referred to inside the stdlib via "_guts.isFastUTF8". I'm not sure if that's currently exposed in the API though.

Looking at the Swift 5 stdlib right now I see a method withContiguousStorageIfAvailable(_:) that seems to do that test, but it's completely undocumented and I don't know if it's appropriate to use for this case.

Oh, I think you just need swift-evolution/0247-contiguous-strings.md at master · apple/swift-evolution · GitHub , no? Which is conveniently currently in review.

3 Likes

That looks like precisely what I want. Thanks!

Also it does confirm that withContiguousStorageIfAvailable can be used for the test right now, although kind of awkwardly.

1 Like

Indeed: swift/StringUTF8.swift at main · apple/swift · GitHub