简体   繁体   中英

Filtering array of functions Swift

When I filter an Array of Functions to exclude a specific function from the array, the filtered array contains no elements. Any idea of why this is happening?

var array: [()->()] = []

array.append(function1)
array.append(function2)

let function: ()
function = function1()
var filteredArray: [()->()] = []
filteredArray = array.filter { $0() != function }

print(filteredArray.count) // 0

Non-Nominal Types cannot be filtered. This is because they are not equatable:

ie Here are some Non-Nominal Types

What you could do is create a struct like so:

struct Method: Hashable, Equatable {
    var name: String
    var method: () -> () // or whatever type you want
    init(_ n: String,_ m: @escaping () -> ()) {
        name = n
        method = m
    }

    // Equatable
    static func == (lhs: Method, rhs: Method) -> Bool {
        return lhs.name == rhs.name
    }

    // Hashable
    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
    }
}

So that the name is what checks if methods are equal. But so much for structs .

If you wanted, you could make a similar class instead to keep track of the reference.


Example code:

func function1() {print("foo")}
func function2() {print("bar")}

var array: [Method] = []

array.append(Method("One", function1))
array.append(Method("Two", function2))

let function: Method
function = Method("One", function1)
var filteredArray: [Method] = []
filteredArray = array.filter { $0 != function}

print(filteredArray.count) // 1

filteredArray.first?.method() // prints "bar"

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