0

If I had a generic class like this:

class Generic<T: Any> {
    var object: T
    init(object: T) {
        self.object = object
    }
}

I could access the object from the initializer like this:

Generic(object: "Hello World").object.count // 11

As this generic class works for Any type, how would I extend all types to return a object of that generic class?

I mean something like this:

extension Any {
    var generic: Generic<Self> {
        Generic(object: self)
    }
}

So I can call:

"Hello World".generic.object.count // 11

I am confused with all the Any, AnyObject, Self, self, Type and so on.

UPDATE:

For example, how would I extend all Comparable with the computed properties array: Array<Comparable>? I am thinking of something like:

extension Comparable {
    var array: Array<Comparable> {
        Array(self)
    }
}
Patia1999
  • 67
  • 1
  • 7
  • 3
    What are you trying to accomplish? – Joakim Danielson Feb 23 '20 at 18:53
  • I would like to find out how I would extend all kinds of classes that a generic class could be constrained to by returning an object of that class using an object of the extended class. – Patia1999 Feb 23 '20 at 19:30
  • For example writing an extension on `Any` so it is capable to return an array consisting of the object. Like `5.array` returns `[5]`. – Patia1999 Feb 23 '20 at 19:35
  • I don't get it. `Generic` is actually an object wrapper. You create an instance with the string and then you get the string back with the `object` property. What is the benefit? – vadian Feb 23 '20 at 19:35
  • There is no benefit. It honestly doesn’t make sense. I still would like to know how this could be done. – Patia1999 Feb 23 '20 at 19:41
  • You should extend actual types then and not the Any – Joakim Danielson Feb 23 '20 at 19:52
  • Thanks! How would I do that? For example, how would I constrain my `array`-extension to `Comparable`? Something like `extension Any { var array: Array { Array(self) } }` – Patia1999 Feb 23 '20 at 20:36
  • I updated my question with another example – Patia1999 Feb 23 '20 at 20:39

1 Answers1

0

You can't extend Any, see https://stackoverflow.com/a/44396546/12846974

Example for Comparable extension:

extension Comparable {
    var array: Array<Self> {
        [self]
    }
}
hell0friend
  • 561
  • 1
  • 3
  • 4