// Dart Iterator
void main(List<String> args) {
Iterable<int> iter = [1, 2, 3];
for (var i in iter) {
print(i);
}
print(iter.runtimeType);
// Unlike a list, you cannot access an element via an iterable object
// using the square brackets []. Instead, you use the elementAt() method:
print(iter.elementAt(1));
List<int> asList = iter as List<int>;
// Iterable 이 추상 클래스라고 했으므로 이를 List 클래스로 형변환도 가능하다.
print(asList[0]);
print("");
List<int> nums = [1, 2, 3];
var it = nums.iterator;
while (it.moveNext()) {
print(it.current);
}
}
// 결과
1
2
3
List<int>
2
1
1
2
3
4
5
// Dart iterator example
//
// Use Iterator<E> interface for getting items one at a time from an object
void main(List<String> args) {
var sentence = Sentence('Dart is great.');
while (sentence.moveNext()) {
print(sentence.current);
}
}
class Sentence implements Iterator {
int _wordIndex = -1;
List<String> _words = [];
Sentence(String str) {
_words = str.split(' ');
}
@override
get current {
if (_wordIndex >= 0 && _wordIndex <= _words.length) {
return _words[_wordIndex];
}
}
@override
bool moveNext() {
if (_wordIndex < _words.length - 1) {
_wordIndex++;
return true;
}
return false;
}
}
// 결과
Dart
is
great.
댓글 영역