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

Opaque parameter declarations

Available from Swift 5.7

Paul Hudson      @twostraws

SE-0341 unlocks the ability to use some with parameter declarations in places where simpler generics were being used.

As an example, if we wanted to write a function that checks whether an array is sorted, Swift 5.7 and later allow us to write this:

func isSorted(array: [some Comparable]) -> Bool {
    array == array.sorted()
}

The [some Comparable] parameter type means this function works with an array containing elements of one type that conforms to the Comparable protocol, which is syntactic sugar for the equivalent generic code:

func isSortedOld<T: Comparable>(array: [T]) -> Bool {
    array == array.sorted()
}

Of course, we could also write the even longer constrained extension:

extension Array where Element: Comparable {
    func isSorted() -> Bool {
        self == self.sorted()
    }
}

This simplified generic syntax does mean we no longer have the ability to add more complex constraints our types, because there is no specific name for the synthesized generic parameter.

Important: You can switch between explicit generic parameters and this new simpler syntax without breaking your API.

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Other changes in Swift 5.7…

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

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.