Understanding () -> Void in Swift
Ⅰ.What is () -> Void in Swift?
It represents a closure that takes no parameters and returns no value.
Let’s break it down:
Part | Meaning |
---|---|
() | No input parameters |
-> | Indicates a return type |
Void | No return value (Void means nothing) |
Ⅱ.In plain language:
() -> Void means:
“A block of code that takes nothing in, returns nothing out — it just runs.”
Example:
1 | let sayHello: () -> Void = { |
This sayHello is a closure of type () -> Void:
- It takes no arguments
- Returns nothing
- Just performs a side effect when called (printing text)
Ⅲ.Bonus: Void is just ()
In Swift:
- Void is just a typealias for an empty tuple ()
- So these two are equivalent:
1 | () -> Void |
Both mean “takes nothing, returns nothing.”
Ⅳ.Comparing Different Closure Types
Closure Type | Meaning | Example |
---|---|---|
() -> Void | No parameters, no return | print(“Hi”) } |
(Int) -> Void | Takes an Int, returns nothing | { num in print(num) } |
(String) -> Int | Takes a String, returns Int | str in str.count } |
(Int, Int) -> Int | Takes two Int, returns Int | { a, b in a + b } |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.