Does Swift have lack of anything equivalent to StringView?

I am rewriting some C++ files using Swift.
The original files are using StringViews to process things.
However, it looks like CharacterView is no longer available since Swift 4.

Any opinions?

Do you mean std::string_view?

It depends what you want to do. If your main concern is avoiding memory duplication, then go ahead and use String, since it and similar types in Swift do copy‐on‐write automatically. For remove_prefix and similar operations, String would be your base and String.SubSequence (which is what you get from subscripting it with a range) is your window into it.

If you also want mutations to be shared between variables, then you will have to wrap it in a minimal class to get reference semantics (or use inout for the relevant function parameters if that will suffice).

I am doubtful CharacterView is of any relevance to translation from C++.

By the end of its lifetime, CharacterView was just a type alias for String. It was part of a family with UnicodeScalarView, UTF8View and UTF16View that permit the string to be used as collections of different kinds of elements. CharacterView was redundant since characters (technically “extended grapheme clusters”) are already the Element of the String type itself. All of these are “views” in the sense that they alter the interface of the string as far as collection operations are concerned, but they all still use value semantics. If a view is stored in a separate variable, changes to it will not affect the string it came from.

5 Likes