æè¿ã¯ããã£ã±ãè¨èªã¬ãã«ã§ãµãã¼ããããããã«ãªã£ã¦ãã¾ã£ã Iterator ã§ãã
ãå¢è£æ¹è¨çJavaè¨èªã§å¦ã¶ãã¶ã¤ã³ãã¿ã¼ã³å ¥éãã§ã¯ãè¨å¿µãã¹ãæåã®ç« ã§ç´¹ä»ããããã¿ã¼ã³ã§ããå ç©ãª(?) Java åãã®è§£èª¬ã¨ãããã¨ãããããã®æ¬ã® Iterator ãã¿ã¼ã³ã®ç« ã§ã¯ãã¯ã©ã¹ãã¤ã³ã¿ãã§ã¼ã¹ãä¸èªç¶ãªã»ã©*1ç»å ´ãã¾ãããSwift ã¯ããè¨èªä»æ§ãæ´ç·´ããããã¨ããããããªãèªç¶ã« Iterator ãã¿ã¼ã³ãé©ç¨ã§ãã¾ãã
ç¬èªã¯ã©ã¹ã§ã¤ã³ãã¯ãµ [ ] ã¨ã for-in æ§æã¨ãã使ããããã«ããããã®ãã³ãã«ãªãããããã¾ããã³ãã£ã½ããªãããã
ã¡ãªã¿ã«åä½ç¢ºèªã¯ Xcode 6 beta 5 ã§è¡ã£ã¦ãã¾ããããããå¤ãï¼ã¾ãã¯æ°ããï¼ãã¼ã¸ã§ã³ã® Xcode ã§ã¯åããªãããç¥ãã¾ããã
// ---------------------------------------- // Book (æ¬) ã¯ã©ã¹ public class Book { private var _name: String public var name: String { get { return _name } } public init(name: String) { self._name = name } } // ---------------------------------------- // BookShelf (æ¬æ£) ã¯ã©ã¹ // SequenceTypeãããã³ã«ãæ¡ç¨ããã®ããã£ã¼ã ãã¤ã³ã public class BookShelf: SequenceType { private var books:[Book] = [] // ããããã£ããã§ã public var capacity: Int { get { return books.capacity } } public var startIndex: Int { get { return books.startIndex } } public var endIndex: Int { get { return books.endIndex } } public var count: Int { get { return books.count } } // ã¤ã³ãã¯ãµ [ ] ã§ã¢ã¯ã»ã¹ã§ããããã«ãªãã public subscript(index: Int) -> Book { get { return books[index] } set { books[index] = newValue } } public subscript(range: Range<Int>) -> Slice<Book> { get { return books[range] } set { books[range] = newValue } } // for-inã§ã¢ã¯ã»ã¹ã§ããããã«ãªãã public func generate() -> GeneratorOf<Book> { var index : Int = 0 return GeneratorOf<Book> { return index < self.books.count ? self.books[index++] : .None } } // âã®ä»£ããã«âã¿ããã«æ¸ãã¦ãOK // â» Arrayã«å§è²ããæ¸ãæ¹ã ã // public func generate() -> IndexingGenerator<[Book]> { // return books.generate() // } public func append(book: Book) { books.append(book) } } // ---------------------------------------- var bookShelf = BookShelf() bookShelf.append(Book(name: "ããããã")) bookShelf.append(Book(name: "ããããã")) bookShelf.append(Book(name: "ãã¼ããã®å¤§åéº")) // [ ]ã§ã¢ã¯ã»ã¹ãã¦ã¿ããã¹ã for var i = 0; i < bookShelf.count; ++i { println(bookShelf[i].name) } for i in bookShelf.startIndex ..< bookShelf.endIndex { println(bookShelf[i].name) } // ã¨ããã for-in æ§æã§ã¢ã¯ã»ã¹ã§ãã for book in bookShelf { println(book.name) }