Fast general function saved as varaible

Given the class:

class First<T> {

}

And the method of the First class:

func second<U>(closure: (value: T) -> U) {

}

How can I save the closure passed as an argument secondso that I can call it later?

+4
source share
2 answers

You will need to declare U in the class instead, so that you have a storage type:

class First<T,U> {
    var f : ((T) -> U)! = nil
    func second(closure: @escaping (T) -> U) {
        self.f = closure
    }
}
+1
source

If a function secondonly works for one type, this is good enough for you, then Matt's answer is responding.

class First<T, U> {
    typealias ClosureType = (value: T) -> U
    var savedClosure: ClosureType? = nil
    func second(closure: ClosureType) {
        savedClosure = closure
    }
}

This does not answer your question as indicated!

The point is: you cannot save a value of an unknown type. But! if the type conforms to a known protocol, you can save it.

protocol P {}

class First<T> {
    typealias ClosureType = (value: T) -> P
    var savedClosure: ClosureType? = nil
    func second<U: P>(closure: (value: T) -> U) {
        savedClosure = closure
    }
}

protocol<> "no protocol at all", typealased Any.

class First<T> {
    typealias ClosureType = (value: T) -> Any
    var savedClosure: ClosureType? = nil
    func second<U>(closure: (value: T) -> U) {
        savedClosure = closure
    }
}

, , ... , , ?

class First<T> {
    typealias ClosureType = (value: T) -> Any
    var savedClosures = [String: ClosureType]()
    func second<U>(closure: (value: T) -> U) {
        savedClosures[String(U)] = closure
    }
}

, : " ? - , , ?"

+1

Source: https://habr.com/ru/post/1651803/


All Articles