WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

nil coalescing operator and multiple function parameters

Forums > Swift

Good evening,

I am trying to incorporate a nil coalescing operator with multiple function parameters. I can make it work with only 1 function parameter but despite multiple efforts can't make it work for multiple.

Appreciate any guidance....

Paul.

Code below:

func albumReleased(year: Int, age: Int) -> String? {
    switch year, age {
        case 2006, 33: return "Taylor Swift"
        case 2007, 34: return "Fearless"
    default: return nil
    }
}
let album = albumReleased(year: 2006, age: 34) ?? "unknown"
print("The album is \(album)")

   

You need to use a tuple in your switch:

func albumReleased(year: Int, age: Int) -> String? {
    //note the parentheses...
    switch (year, age) {
    case (2006, 33): return "Taylor Swift"
    case (2007, 34): return "Fearless"
    default: return nil
    }
}
let album = albumReleased(year: 2006, age: 34) ?? "unknown"
print("The album is \(album)")

   

thanks. really appreciate the help!

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.