# How to create generic functions within a non-generic struct

**URL:** <https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524>\
**Category:** Using Swift\
**Tags:** generics\
**Created:** [May 15, 2020, 6:17pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524 "2020-05-15T18:17:45Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![dhoerl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dhoerl/32/8643_2.png) [@dhoerl](https://forums.swift.org/u/dhoerl)\
**Post date:** [May 15, 2020, 6:17pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/1 "2020-05-15T18:17:45Z")

</div>

This is what I'm trying to do unsuccessfully:

> struct Foop {  
> func callAsFunction(val: T) -\> T {  
> return calc(val)  
> }
> 
> ```
> func calc<T: Int>( _ val: T) -> T {
> let g = val + 5
> return val
> }
> 
> func calc<T: Double>( _ val: T) -> T {
> let g = val + Double(5)
> return val
> }
> 
> ```
> 
> }

The types I have are going to be type aliased blocks if it matters.

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [May 15, 2020, 6:23pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/2 "2020-05-15T18:23:19Z")

</div>

You want a protocol constraint. If there is an existing protocol, use it. If not, make a new one.

```swift
func addFive<T: Numeric>(_ val: T) -> T {
  return val + 5
}

```

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [May 15, 2020, 7:16pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/3 "2020-05-15T19:16:24Z")

</div>

To add, you want `calc` as a protocol member since you want to use dynamic dispatch:

```swift
protocol Calcable {
  func calc() -> Self
}

extension Double: Calcable {
  func calc() -> Double {
    self + 0.5
  }
}

struct Foo {
  func callAsFunction<T: Calcable>(val: T) -> T {
    val.calc()
  }
}

```

---

<div class="post-metadata">

**Author:** ![dhoerl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dhoerl/32/8643_2.png) [@dhoerl](https://forums.swift.org/u/dhoerl)\
**Post date:** [May 15, 2020, 7:20pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/4 "2020-05-15T19:20:29Z")

</div>

Lantua - thanks!

OK - getting close! My types are not Numerics - they are:

typealias ArrayVoidClosure = ((NSArray?) -\> Void)  
typealias AnyVoidClosure = ((Any?) -\> Void)  
...

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [May 15, 2020, 7:33pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/5 "2020-05-15T19:33:36Z")

</div>

Please describe in words what you want. Not in code, in words.

You cannot add 5 to an `ArrayVoidClosure`.

If you want help achieving something, you need to explain what it is you want to achieve.

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [May 15, 2020, 7:40pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/6 "2020-05-15T19:40:50Z")

</div>

Do you mean you want to just call them? Or to treat them differently before/after calling them?

If you want to just call them, you can use generic on the related type, argument and/or return type:

```swift
func calc<T>(closure: (T?) -> Void) {
  ...
  closure(someValue)
}

```

If you want to treat them differently within the same function, that'd require some protocol gymnastic since you can't conform any of the components of `AnyVoidClosure` (You can't conform a closure or `Any` to any protocol). The simplest solution would be to use `==` on its metatype. It doesn't scale well, but I'd say it's much simpler if you have only a few types:

```swift
func calc<T>(closure: (T?) -> Void) {
  if T.self == NSArray.self {
    ...
  } else if T.Self == Any.self {
    ...
  }
}

```

---

<div class="post-metadata">

**Author:** ![dhoerl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dhoerl/32/8643_2.png) [@dhoerl](https://forums.swift.org/u/dhoerl)\
**Post date:** [May 15, 2020, 7:41pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/7 "2020-05-15T19:41:18Z")

</div>

Was trying to make a simple example, bad choice. Here is a real world example without any generics - I keep think I should be able to make it some or mostly generic:

typealias XClosure = ((NSArray?) -\> Void)  
typealias YClosure = ((Any?, Error?) -\> Void)

struct Str {  
func callAsFunction(val: @escaping XClosure) -\> XClosure {  
return wrapper(val)  
}  
func callAsFunction(val: @escaping YClosure) -\> YClosure {  
return wrapper(val)  
}

```
private func wrapper(_ originalHandler: @escaping XClosure) -> XClosure {
    let newHandler: XClosure = { a in
        DispatchQueue.main.async {
            originalHandler(a)
        }
    }
    return newHandler
}
private func wrapper(_ originalHandler: @escaping YClosure) -> YClosure {
    let newHandler: YClosure = { a, b in
        DispatchQueue.main.async {
            originalHandler(a, b)
        }
    }
    return newHandler
}

```

}

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [May 15, 2020, 8:04pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/8 "2020-05-15T20:04:30Z")

</div>

That'd be tricky, since functions with different arity (number of arguments) doesn't have much in common (right now). Though you can combine ones with the same arity:

```swift
/// With 1 argument
func wrapper1<T>(_ original: @escaping (T) -> ()) -> (T) -> () {
  ...
}

/// With 2 arguments
func wrapper2<T, U>(_ original: @escaping (T, U) -> ()) -> (T, U) -> () {
  ...
}

```

---

<div class="post-metadata">

**Author:** ![dhoerl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dhoerl/32/8643_2.png) [@dhoerl](https://forums.swift.org/u/dhoerl)\
**Post date:** [May 15, 2020, 8:42pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/9 "2020-05-15T20:42:35Z")

</div>

That's a great idea! Will definitely remove lots of duplicated code!

---

<div class="post-metadata">

**Author:** ![dhoerl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dhoerl/32/8643_2.png) [@dhoerl](https://forums.swift.org/u/dhoerl)\
**Post date:** [May 15, 2020, 9:53pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/10 "2020-05-15T21:53:46Z")

</div>

> [@Lantua](#):
>
> /// With 1 argument func wrapper1(\_ original: @escaping (T) -\> ()) -\> (T) -\> () { ... } /// With 2 arguments func wrapper2\<T, U\>(\_ original: @escaping (T, U) -\> ()) -\> (T, U) -\> () { ... }

I got it to compile, not tested if it really works or not. But interesting result. Where you had different function names, I wanted to use one name as its not obvious how many arguments each closure takes from looking at its name. When I tried that, I got an "ambiguous" warning. But, I found it I added dummy unused parameters to each function, depending on the Generic types, then it all compiles fine. So for the function with two generics:

func callAsFunction\<T, U\>(completionHandler originalHandler: @escaping (T, U) -\> Void, trace: Trace = Trace(), dummy1: Int = 0) -\> (T, U) -\> Void {

Then for the one with 3:

func callAsFunction\<T, U, V\>(completionHandler originalHandler: @escaping (T, U, V) -\> (), trace: Trace = Trace(), dummy1: Int = 0, dummy2: Int = 1) -\> (T, U, V) -\> ()

Anyway, this saved me from writing over a dozen non-generics functions!

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [May 15, 2020, 10:26pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/11 "2020-05-15T22:26:22Z")

</div>

Ah right, you can convert multi-argument functions to single-argument ones due to a [revision to SE-0110](https://lists.swift.org/pipermail/swift-evolution-announce/2017-June/000386.html) so the call site is rightfully ambiguous. You can't convert it back so I think that wouldn't meet your expectation since the wrapped functions become single-argument:

```swift
let foo = wrapper1 { (a: Int, b: String) in }
// Needs to call foo((0, "test")), not foo(0, "test")

```

You could put just one dummy variable on the single-arity function since type checker prefer functions with less defaulted arguments, and there's no ambiguity between others like 2 vs 3-arity.

```swift
func wrapper<T>(type: T.Type = T.self, _ original: @escaping (T) -> ()) -> (T) -> () {
  ...
}

func wrapper<T, U>(_ original: @escaping (T, U) -> ()) -> (T, U) -> () {
  ...
}

func wrapper<T, U, V>(_ original: @escaping (T, U, V) -> ()) -> (T, U, V) -> () {
  ...
}

```

While we're at it, we might as well use `T.Type` as the dummy variable since we can use it to guide type checker should the need arise.

Though I'd suggest that you separate (only) the single-argument function into a separate name since that's where all this mess come from, and the _fix_ is dealing with the nuance of type checker, which is not guaranteed to stay.

---

<div class="post-metadata">

**Author:** ![dhoerl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dhoerl/32/8643_2.png) [@dhoerl](https://forums.swift.org/u/dhoerl)\
**Post date:** [May 17, 2020, 1:40pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/12 "2020-05-17T13:40:49Z")

</div>

Well, my post you responded to was wrong. I am using additional parameters (recording file name, line number, in this call), but the dummy parameters didn't actually help me. What did was actually defining the expected return type:

let foo: SomeClosureType = wrapper(...)

I'm overloading callAsFunction() with every wrapper (4 of them) and clang is fine with it! Still to test execution!

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [May 17, 2020, 1:46pm UTC](https://forums.swift.org/t/how-to-create-generic-functions-within-a-non-generic-struct/36524/13 "2020-05-17T13:46:09Z")

</div>

My explanation should still apply equally well. And I'd still suggest that you separate a one-argument case (maybe by using a different name?) since it'd otherwise create ambiguous/unexpected overload choice without type annotation.
