3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

独自クラスにCollectionの振る舞いを持たせる

Last updated at Posted at 2017-12-01

独自に作成したクラスをCollectionとして扱いたいことって多いですよね。
そんなときはCollectionプロトコルを継承することで実現が可能です。

・Collection
https://developer.apple.com/documentation/swift/collection

以下実装手順になります。

associatedtypeに型を指定

独自クラスをCollectionとして扱うには、associatedtypeとして宣言されている
Element および Index に実際の型を指定する必要があります。

typealias Element = Book
typealias Index = Int

こんな感じですね。

startIndex 及び endIndex を指定

Collectionの開始位置、終了位置を指定する必要があります。

var startIndex: Int { return list.startIndex }
var endIndex: Int { return list.endIndex }

サブスクリプトを定義

array[0]みたいにアクセスするために必要です。

subscript (position: Index) -> Element {
    return list[position]
}

index(after:)を定義

func index(after index: Int) -> Index {
    return list.index(after: index)
}

サンプルコード

全体でみるとこんな感じになります

import UIKit

class Book {
    var title: String?
}

class BookCollection: Collection {
    
    typealias Element = Book
    typealias Index = Int
    
    private var list: [Book] = []
    
    var startIndex: Int { return list.startIndex }
    var endIndex: Int { return list.endIndex }
    
    subscript (position: Index) -> Element {
        return list[position]
    }
    
    func index(after index: Int) -> Index {
        return list.index(after: index)
    }
    
    func append(newElement: Element) {
        list.append(newElement)
    }
}

var collection = BookCollection()
print(collection.isEmpty ? "empty" : "not empty") // => empty
for i in 0..<10 {
    let b = Book()
    b.title = "title\(i)"
    collection.append(newElement: b)
}

print(collection.count) // => 10
print(collection.isEmpty ? "empty" : "not empty") // => not empty
print(collection.first!.title!) // => title0
collection.forEach { (b) in
    // do something
}

3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?