Why doesn't Dart String class implement the iterable interface? It seems like there is an obvious notion of iteration for strings, i.e. just return each character in turn.
Maybe not that terse as you would like
String s = 'foo';
s.codeUnits.forEach((f) => print(new String.fromCharCode(f)));
s.runes.forEach((f) => print(new String.fromCharCode(f)));
To answer the "Why":
The Iterable interface is a fairly heavy-weight interface (many members) that is intended for collections of elements.
While a String can be seen as a List of characters (but Dart doesn't have a type for characters, so it would really be "List of single-character Strings"), that is not its main usage, and also being an Iterable would clutter the actual String methods.
A better solution would be to have a List view of a String. That is fairly easily doable:
class StringListView extends ListBase<String> {
final String _string;
StringListView(this._string);
@override
String operator [](int index) => _string[index];
@override
int get length => _string.length;
@override
set length(int newLength) {
throw UnsupportedError("Unmodifiable");
}
@override
void operator []=(int index, String v) {
throw UnsupportedError("Unmodifiable");
}
}
Would be even easier if the libraries exposed the UnmodifiableListBase used to make UnmodifiableListView.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With