简体   繁体   中英

Check if the generic type is a function type in Swift

I have defined a generic class as follows

class A<T:Any>{
   var value:T? 
}

I would like to know how I could limit T to be of a function type and can write code like value() in Class A.

let a = A<()->()>()

Referring to Apple's Documentation :

Generic code enables you to write flexible, reusable functions and types that can work with any type , subject to requirements that you define.

This is the main purpose of using Generics.

In your case, probably, this is the not right way of how to use them. You might want to make more simple:

typealias funcion = ()->()

class A {
    private var value:funcion?

    init(value: @escaping funcion) {
        self.value = value
    }

    func doSomething() {
        print("do something 01")

        if let iplementedValue = value {
            iplementedValue()
        }

        print("do something 02")
    }
}

Instantiation:

let aObject = A(value: {
    print("I want to this in the middle of my \"doSomething\"")
})

aObject.doSomething()

The output should looks like:

do somthing 01
I want to this in the middle of my "doSomething"
do somthing 02

Hope that helped.

I was having a similar problem, I ended up solving it like so:

First I defined a generic type representing a function which accepts a single parameter, and return value:

typealias Monad<A, R> = (A) -> (R)

I then defined my class to take a generic type parameter for the input type. In my case, every function passed was going to return void so I didn't need two type parameters.

class HoldsMyCallback<A> {
    let callback: Monad<A, Void>

    init(callback: @escaping Monad<A, Void>) {
        self.callback = callback
    }
}

...

let funcKoozie = HoldsMyCallback<Int> {
    print("keep my \($0) function cold")
}

funcKoozie.callback(1)

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