This cannot be done with an extension within the existing protocol and generic system in Swift - you cannot add additional restrictions to a universal subtype of a type, so you cannot extend Array with a method that requires its contents to be Equatable .
You can see this restriction in action with the built-in array type - there is no myArray.find(element) method, but there is a global find() function that accepts a collection and an element with a common restriction that the collection is Equatable elements:
func find<C : CollectionType where C.Generator.Element : Equatable>(domain: C, value: C.Generator.Element) -> C.Index?
You can do this for your method - you just need to write a similar top-level function:
func replaceObjectWithObject<C : RangeReplaceableCollectionType where C.Generator.Element : Equatable>(inout collection: C, obj1: C.Generator.Element, obj2: C.Generator.Element) { if let index = find(collection, obj1) { removeAtIndex(&collection, index) insert(&collection, obj2, atIndex: index) } } var myArray = [1, 2, 3, 4, 5] replaceObjectWithObject(&myArray, 2, 7)
source share