在Swift中使用forEach实现CollectionType,给出非可选闭包变量

时间:2016-03-11 06:58:58

标签: swift collections foreach

class SelectableArray: CollectionType, MutableCollectionType {
    private var elements = Array<Element>()

    convenience init(elements: [Element]) {
        self.init()
        self.elements = elements
    }

    var startIndex: Int { return elements.startIndex }
    var endIndex: Int { return elements.endIndex }
    subscript (index: Int) -> Element? {
        get {
            return elements[index]
        }

        set {
            elements[index] = newValue!
        }
    }
}

以上类forEach给出以下内容:

let a = SelectableArray<String>(elements: ["a","b"])
a.forEach { (String?) -> () in
    <#code#>
}

我想知道为什么Array forEach是(String) - &gt; Void但我的是(String?) - &gt;虚空。我怎样才能成为(String) - &gt;无效?

1 个答案:

答案 0 :(得分:0)

我明白了,subscript (index: Int) -> Element?应该是subscript (index: Int) -> Element