Local functions now support overloading
About 2 min
Local functions now support overloading 관련
HACKING WITH SWIFT
What's new in Swift?
Local functions now support overloading | Changes in Swift 5.4
Local functions now support overloading
Available from Swift 5.4
SR-10069 requested the ability to overload functions in local contexts, which in practice means nested functions can now be overloaded so that Swift chooses which one to run based on the types that are used.
For example, if we wanted to make some simple cookies we might write code like this:
struct Butter { }
struct Flour { }
struct Sugar { }
func makeCookies() {
func add(item: Butter) {
print("Adding butter…")
}
func add(item: Flour) {
print("Adding flour…")
}
func add(item: Sugar) {
print("Adding sugar…")
}
add(item: Butter())
add(item: Flour())
add(item: Sugar())
print("Come and get some cookies!")
}
makeCookies()
Prior to Swift 5.4, the three add()
methods could be overloaded only if they were not nested inside makeCookies()
, but from Swift 5.4 onwards function overloading is supported in this case as well.
Swift 5.4 also lets us call local functions before they are declared, meaning that we can now write code like this if needed:
func makeCookies2() {
add(item: Butter())
add(item: Flour())
add(item: Sugar())
func add(item: Butter) {
print("Adding butter…")
}
func add(item: Flour) {
print("Adding flour…")
}
func add(item: Sugar) {
print("Adding sugar…")
}
}
makeCookies2()
Other Changes in Swift 5.4
Improved implicit member syntax | Changes in Swift 5.4
Improved implicit member syntax
Multiple variadic parameters in functions | Changes in Swift 5.4
Multiple variadic parameters in functions
Creating variables that call a function of the same name | Changes in Swift 5.4
Creating variables that call a function of the same name
Result builders | Changes in Swift 5.4
Result builders
Property wrappers are now supported for local variables | Changes in Swift 5.4
Property wrappers are now supported for local variables
Packages can now declare executable targets | Changes in Swift 5.4
Packages can now declare executable targets