Is there a swift protocol which Array and ArraySlice both implement

Viewed 197

What type should I use in swift 5 if I want a function to accept either a [Double] or an ArraySlice<Double>?

In other words, is there some type I can use which would allow me to combine both of the following declarations into one, so that the function can be called with one or the other?

func appendToX(_ data: ArraySlice<Double>) 
func appendToX(_ data: [Double]) 
2 Answers

As @MartinR said in the comment, they both conform to RandomAccessCollection protocol, but you need to use generics in your function due to the fact that RandomAccessCollection has Self or associated type requirements:

func appendToX<T: RandomAccessCollection>(_ data: T) where T.Element == Double, T.Index == Int {

}

Swift 5.6

Thanks to several recent improvements to Swift's generics UI, you can replace your original two function declarations with the following:

func appendToX(_ data: any RandomAccessCollection<Double>) 
Related