Help us understand the problem. What is going on with this article?

Swiftでデザインパターン イテレーターパターン

More than 1 year has passed since last update.

こちらを参考に、Swiftで簡単に書き直し
https://qiita.com/sugihara-masaki/items/0d3982276eb7494dc25d

イテレーターパターン

  • コンテナの内部表現を隠蔽して要素へのアクセスを提供するパターン
  • 「リリース日が最近の順」など順番の項目ごとにIteraterクラスを作成し、そこで実装することで、関心を分離する
struct Movie {
    var title: String
    var publishedYear: Int = 0
}

struct MovieAggregate {
    var movies: [Movie] = [Movie]()

    mutating func addMovie(movie: Movie) {
        self.movies.append(movie)
    }

    func getByIndex(index: Int) -> Movie {
        return self.movies[index]
    }

    func size() -> Int {
        return self.movies.count
    }
}

struct RecentIterator {
    var sortedMovies: [Movie] = [Movie]()
    var index: Int = 0

    init(aggregate: MovieAggregate) {
        self.sortedMovies = aggregate.movies.sorted(by: {
            $0.publishedYear > $1.publishedYear
        })
        self.index = 0
    }

    func hasNext() -> Bool {
        return self.index < self.sortedMovies.count
    }

    mutating func nextItem() -> Movie {
        let item = self.sortedMovies[index]
        self.index = index + 1
        return item
    }
}

var movieAggregate = MovieAggregate()

let shawshank = Movie(title: "ショーシャンクの空に", publishedYear: 1994)
movieAggregate.addMovie(movie: shawshank)

let matrix = Movie(title: "マトリックス", publishedYear: 1999)
movieAggregate.addMovie(movie: matrix)

let outrage = Movie(title: "アウトレイジ", publishedYear: 2010)
movieAggregate.addMovie(movie: outrage)

var iterator = RecentIterator(aggregate: movieAggregate)

while iterator.hasNext() {
    let movie = iterator.nextItem()
    print(movie.title)
}

bla-bo
Blabo!はちょっとしたひらめきで、商品をつくれるコミュニティです。
https://bla.bo/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away