简体   繁体   中英

How do I implement the filter function in Swift

To gain a better understanding of Swift, I've extended SequenceType to add my own versions of map , reduce and forEach functions. However, the filter function is different in that it returns an array of Self.Generator.Element . Here's what I have so far:

extension SequenceType {
    public func myFilter(@noescape includeElement: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.Generator.Element] {
        var array = [Self.Generator.Element]()
        for element in self {
            do {
                if try includeElement (element) {
                    array.append(element)
                }
            }
        }
        return array
    }
}

The statement var array = [Self.Generator.Element]() produces an "Invalid use of () to call a value of non-function type [Self.Generator.Element.Type]" error. My question is how do I create/add to/return an array of Self.Generator.Element ?

Not sure why, but Xcode is fine with following syntax:

extension SequenceType {
    public func myFilter(@noescape includeElement: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.Generator.Element] {
        var array : [Self.Generator.Element] = []
        for element in self {
            do {
                if try includeElement (element) {
                    array.append(element)
                }
            }
        }
        return array
    }
}

The only change is the array declaration ( var array : [Self.Generator.Element] = [] ).

Swift's type inference is getting confused about what you mean. This could mean two things:

var array = [Self.Generator.Element]()

You might mean (and do mean) that you want to call the constructor for the type Array<Self.Generator.Element> .

But you might mean (and the compiler thinks you mean) that you want to create an array of Self.Generator.Element.Type and then you want to call it as a function.

I don't remember this being a compiler confusion in the past, and it may be a regression. That said, it is ambiguous (though only one really makes sense in the end, and I would think you'd need to have said Generator.Element.self there to refer to the type, so maybe it's a real compiler bug). You can remove the ambiguity by using the preferred way to initialize arrays, by using their type:

var array: [Self.Generator.Element] = []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM