func doSomething() -> String { ... }
async
version:
async func doSomething() -> String { ... }
It just a syntactic sugar for Future<T>
:
func doSomething() -> Future<String> { ... }
// lambda or closure
let doSomething_Async_Closure: Future<String> = async {
// return getStringFuture<String>().await()
return await getStringFuture<String>() // syntactic sugar for `Future<String>.await()`
}
let doSomething_Async_Closure2: Future<String> = async { () -> String in
// return getStringFuture<String>().await()
return await getStringFuture<String>() // syntactic sugar for `Future<String>.await()`
}
Unfortunately, { async in ... }
already has a meaning as a closure that has a single parameter that we name async
. It might not happen in practice, but another syntactic micro-optimization on closure syntax that conflicts with an existing syntactic micro-optimization doesn't seem worthwhile to me.
// also solve the ploblem describe in above quote:
let doSomething_Closure2 = async { async -> String in
// return getStringFuture<String>().await()
return await getStringFuture<String>() // syntactic sugar for `Future<String>.await()`
}
and avoid the async
in function signature in closure
{ () async -> Int in // <---- here
print("here")
return await getIntFuture()
}
func doSomething() throws -> String { ... }
as we known, it just a syntactic sugar for Result<T,E>
in swift stdlib:
func doSomething() -> Result<String, Error> { ... }
async
version:
async func doSomething() throws -> String { ... }
It just an other syntactic sugar for Future<T>
:
func doSomething() -> Futrue<Result<String, Error>> { ... }
// usage:
let usage_Closure = async { () throws in
let result: Result<String, Error> = await doSomething()
let str: String = try result.get()
return str
}
// equals to
let usage_Closure2 = async { () throws in
return try await doSomething()
}
Note:
It is
try await
not
await try
What is
async {
...
}
?
It is a init
function in Futrue<T>
:
class Future<T> {
public init(body: () -> T)
}
So
async func doSomething() throws -> String { ... // dosth }
// and
let future: Future<Result<String, Error>> = async {
... // dosth
}
It is just another syntactic sugar:
func doSomething() throws -> String { ... }
let future: Future<Result<String, Error>> = Future.init {
return Result {
try doSomething()
}
}