is it possible to create a generic closure in Swift?

后端 未结 4 1319
一生所求
一生所求 2020-12-30 19:49
func myfunc(i:T) -> T {
    return i
}

is it possible to make this generic function a closure?

let myfunc = {          


        
4条回答
  •  半阙折子戏
    2020-12-30 20:30

    As mentioned, variables in Swift cannot be generic, so creating a closure, whose generic types are specified by the caller is not possible. However, there are workarounds:

    With SE-253, it is possible to make arbitrary (nominal) types callable. So instead of declaring a generic closure, we can declare a (non-generic) struct that has a generic callAsFunction method:

    struct MyFunc {
        func callAsFunction(_ i: T) -> T {
            return i
        }
    }
    

    Now, we can declare a non-generic variable that we can call with a generic value:

    let myFunc = MyFunc()
    let x = myFunc(42) // -> Int
    let y = myFunc("foo") // -> String
    

    Note that this workaround doesn't apply to all situations, but it can be helpful in some.

提交回复
热议问题