Hi,
For a long time I had been classes when ever I had asynchronous code, like fetching data etc.
My understanding (could be wrong)
-
struct
can be used for async functions - When using
struct
need to make sure we don't pass them around as they would be copied (value type) and the call to the original async function might have been initiated in a different instance of the struct. - As long the same struct instance is held somewhere async functions should be ok
Questions
- Can a struct have async functions in them (see example below)?
- Is there anything that I need to keep in mind while using struct for async functions?
- Is my understanding (stated above correct)?
Code
func f1(completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
print("f1 done")
completion()
}
}
func f2() async {
try? await Task.sleep(nanoseconds: 2_000_000_000)
print("f2 done")
}
struct Service {
func f3() {
f1 {
print("f3 done")
}
}
func f4() async {
await f2()
print("f4 done")
}
}
let s = Service()
s.f3()
await s.f4()