2

Is it possible when writing an extension to Array to limit the extension just to a particular Array type? What I am trying to do is add an extension to Array that only works on Arrays of type [SKTexture].

I don't want the extension to do anything with Arrays containing other types (i.e. [Int], [Double], [String], etc.)

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294
  • 2
    You can't, sadly. I also desire this functionality. Some of the better attempts exist here: http://stackoverflow.com/questions/24047164/extension-of-constructed-generic-type-in-swift – Andrew Robinson Apr 28 '15 at 13:53
  • Thanks Andrew, I will have a look. – fuzzygoat Apr 28 '15 at 14:04
  • Same problem here: http://stackoverflow.com/questions/24938948/array-extension-to-remove-object-by-value (possible duplicate?) From the top-voted answer: *"You cannot write a method on a generic type that is more restrictive on the template."* – Martin R Apr 28 '15 at 14:51

1 Answers1

0

I agree with the comments above that it is not possible to write an extension like this, but wanted to suggest using a global function instead, with the option of currying it for greater flexibility.

For some background information, see this blog post by Ole Begemann where he notes that in Swift,

Instance methods are just curried functions that take the instance as the first argument.

So from Swift's point of view there is no difference between instance.function() and function(instance)().

I don't know what you are trying to do, but a global function that looks like this...

func skTextureFunc(textures: [SKTexture])(arg: SomeArgType) { }

...is, for all intents and purposes, exactly the same as an instance method that can be bound to a particular instance of [SKTexture].

And if you want, you can partially apply the function to a specific instance of [SKTexture] that you will be using repeatedly and then use it as if it were an instance method bound to that instance. So, for example:

class Example {
    var localSKTextureFunc: SomeArgType -> () {
        return skTextureFunc(textureArray)
    }

    let textureArray = [SKTexture]()
}

So globally you can always use the curried function, and locally (inside a class) you can bind the curried function to a specific instance of a class.

I know that's not exactly what you asked, but I think it is the best work around for the fact that we can't write extensions like the one you describe.

Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43