しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

EmptyCollectionという常に空な配列

Swift言語について調べていたらEmptyCollectionという不思議な物を見つけたので動かしてみました。

初期化は下の通りです。
appendメソッドはないので要素の追加はできません。

let arr = EmptyCollection<Int>()
arr.count

EmptyCollectionの定義は下の通りです。
initも通常のものしかないので本当に値の追加方法あなさそうです。

/// A collection whose element type is `Element` but that is always empty.
public struct EmptyCollection<Element> : CollectionType {
    /// A type that represents a valid position in the collection.
    ///
    /// Valid indices consist of the position of every element and a
    /// "past the end" position that's not valid for use as a subscript.
    public typealias Index = Int
    /// Construct an instance.
    public init()
    /// Always zero, just like `endIndex`.
    public var startIndex: Index { get }
    /// Always zero, just like `startIndex`.
    public var endIndex: Index { get }
    /// Returns an empty *generator*.
    ///
    /// - Complexity: O(1).
    public func generate() -> EmptyGenerator<Element>
    public subscript (position: Index) -> Element { get }
    /// Return the number of elements (always zero).
    public var count: Int { get }
}

extension EmptyCollection : _Reflectable {
}