Reputation: 6361
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.
Upvotes: 4
Views: 2854
Reputation: 2905
You can easily convert Dart to List
by using .split('')
and you can use it as Iterable
, because List
is a subclass.
String s = 'foo';
for(String d in s.split('')) {
print(d);
}
Upvotes: 2
Reputation: 71643
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
.
Upvotes: 5
Reputation: 657248
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)));
Upvotes: 4