How do we write type specific extensions to Array?

So I'd like to add an extension to Array but only when the Array is an array of a specific type. I tried starting with [Int].

In a playground:


extension Array where Generator.Element:Int {


mutating func addInts() {

self.append(1)

self.append(2)

}


}


var myIntArray = [Int]()

myIntArray.addInts()

Results in an error "[Int]" doesn't have a member named 'addInts'.

Any ideas? Is this even possible?

As a pattern though, using the ":" method is lots less flexible. You can only ever add MyContent to the array. I want the protocol to be the thing which defines what can be placed in the Array not anything else.


Still wish it was as simple as :

extension Array where Element == AnyTypeIWant


This has been a really great learning experience.

Cheers!

You CAN define the array as an array of items of your protocol type:


protocol MyProtocol {}
struct MyContent : MyProtocol {
  let content = 1
}
struct MyOtherContent : MyProtocol {
  let content = 2
}
var myArray = [MyProtocol]()
myArray.append(MyContent())
myArray.append(MyOtherContent())
myArray.append(String()) // Error here because String does not conform to MyProtocol


But what you CAN'T do is use that addItems method as written. And logically so: It has no idea what type of items to create. "MyProtocol" simply defines an interface and can't be instantiated on its own.

How do we write type specific extensions to Array?
 
 
Q