TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Local functions now support overloading

Available from Swift 5.4

Paul Hudson      @twostraws

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()
Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.4…

Download all Swift 5.4 changes as a playground Link to Swift 5.4 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.