Home > database >  Is it possible to Extend functions in swift
Is it possible to Extend functions in swift

Time:01-20

I would like to ask if it's possible to extend functions or have some way to use them like this. Because I don't want to open task closure for every async function. I couldnt find any Nominal Type for functions in swift to extend.


func doSometingAsync() async -> Void {

}


// Non - desired
Task {
   await doSometingAsync()
}


func makeItAsync() {
   Task {
      await self()
   }
}

// Desired
doSometingAsync().makeItAsync()

// Extending those also not working
typealias Function = () -> Void
typealias AsnyFunction = () async -> Any?

Thank you!

CodePudding user response:

You definitely shouldn't create a Task for every async function. If you are, something else is likely wrong. But your desired syntax is definitely impossible. You cannot attach methods to functions. Swift does not support it. It's not logically impossible (Go uses it regularly). It's just not a Swift feature, and I expect it will never be a Swift feature. It's not the direction Swift is evolving.

The following is legal if you want it:

func makeAsync(_ f: @escaping () async -> Void) {
    Task { await f() }
}

makeAsync(doSometingAsync)

This is shorter than your proposed solution by a few characters, if that matters to you.

All said, though, if you need this a lot, you probably have an async design problem, and should investigate that.

  • Related