Return in function without return value in Swift
The following signatures all return an instance of the empty tuple ()
(typealiased as Void
).
func implicitlyReturnEmptyTuple() { }
func explicitlyReturnEmptyTuple() {
return ()
}
func explicitlyReturnEmptyTupleAlt() {
return
}
In all of the three above, the return type of the function, in the function signature, has been omitted, in which case it is implicitly set to the empty tuple type, ()
. I.e., the following are analogous to the three above
func implicitlyReturnEmptyTuple() -> () { }
func explicitlyReturnEmptyTuple() -> () {
return ()
}
func explicitlyReturnEmptyTupleAlt() -> () {
return
}
With regard to your comment below (regarding body of implicitlyReturnEmptyTuple()
where we don't explicitly return ()
); from the Language Guide - Functions: Functions without return values:
Functions are not required to define a return type. Here’s a version
of thesayHello(_:)
function, calledsayGoodbye(_:)
, which prints
its ownString
value rather than returning it:func sayGoodbye(personName: String) {
print("Goodbye, \(personName)!")
}
...
Note
Strictly speaking, the
sayGoodbye(_:)
function does still return a
value, even though no return value is defined. Functions without a
defined return type return a special value of typeVoid
. This is
simply an empty tuple, in effect a tuple with zero elements, which can
be written as()
.
Hence, we may omit return ...
only for ()
-return (Void
-return) function, in which case a ()
instance will be returned implicitly.
Swift function with Void return type versus no return type
Simply, there is no difference. -> Void
is just an explicit way of saying that the function returns no value.
From docs:
Functions without a defined return type return a special value of type Void. This is simply an empty tuple, in effect a tuple with zero elements, which can be written as ().
Thus, these three function declarations below are same:
func someFunc() {}
func someFunc() -> Void {}
func someFunc() -> () {}
swift calling async function without a return value
What you're describing is a Task. For example:
Task { await `do`() }
stuff()
This will run do()
concurrently with stuff()
. If you need to keep track of when do()
completes, you can await the task's value:
let task = Task { await `do`() }
stuff()
await task.value // Doesn't actually return anything, but will block
This kind of Task runs in the context of the current Actor, which is usually what you want. If you want something independent of the current Actor, you can use Task.detached()
instead.
If you've previously used DispatchQueues, in many of the places you would have written queue.async { ... }
, you can now write Task { ... }
. The new system is much more powerful, but it maps fairly nicely to the old system if you want it to.
Is Return keyword mandatory for swift functions with return value
It's called Functions With an Implicit Return:
If the entire body of the function is a single expression, the function implicitly returns that expression.
Added in swift 5.1. You can check the proposal
Optional try for function with no return value
There is no reason for the compiler to complain. The return type
of
func throwingVoidFunction() throws { ... }
is Void
and therefore the type of the expression
try? throwingVoidFunction()
is Optional<Void>
, and its value is nil
(== Optional<Void>.none
) if an error was thrown while evaluating the expression,
and Optional<Void>.some()
otherwise.
You can ignore the return value or test it against nil
. An
example is given in An elegant way to ignore any errors thrown by a method:
let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)
Async/Await function without a return | Swift 5.5
This is what worked the best:
try await withUnsafeThrowingContinuation { (continuation: UnsafeContinuation<Void, Error>) in
Related Topics
Simplest Way to Implement a "Read More" Button to Expand a Uitextview in iOS Swift 2
Uilocalnotification: Playing a Custom Audio File Saved in Documents Directory
Get All Urls for Resources in Sub-Directory in Swift
Load Large 3D Object .Scn File in Arscnview Aspect Fit in to the Screen Arkit Swift iOS
Detect When Uitableviewcell Did Load
How to Get Label Name from Button
How to Call Rating View from JSON and Show the Rating in My Table View
Set the Center of a Uibutton Programmatically - Swift
iOS with Parse. Pfuser.Currentuser() Not Getting Cached. Returns Nil After App Restart
Cannot Set Color of Button's Label Inside Menu in Swiftui
Change Push Notification Sound File, Only Works After iOS Reboot
Swift: Programmatically Create Uilabel Fixed Width That Resizes Vertically According to Text Length
How to Use Key-Value Coding in Swfit 4.0
Read Logs Using the New Swift Os_Log API
Firebase Get Child Id Swift iOS