0

If I want to add an extension to every object I can do the following:

extension AnyObject
{
     func myFunc() { ... }
}

Is there something similar where I can add a function to every Enum? In other words, what is the base "class" for every enum?

Matthijn
  • 3,126
  • 9
  • 46
  • 69

1 Answers1

5

First of all, note that you cannot do an extension to AnyObject as above, as AnyObject is a protected protocol (to which all classes implicitly conform) rather than a type. See e.g.

Now, you could, however, extend any specific type as you show above, e.g., extension Int { ... }. However enum is not a type; rather a "container" of ordered raw representable values. So a more valid comparison could be "If I want to add an extension to every class, by extension class ...", which is, naturally, trickier.

Now, all enumerations with a rawValue and an initializer by rawValue conforms to protocol RawRepresentable, so you could extend this protocol for specific types of raw values:

extension RawRepresentable where RawValue == Int {
    var sqrt: Double {
        return pow(Double(rawValue),(1/2))
    }
}

And this extension property would be available to all enumerations that explicitly use the same raw value type, in this case, Int:

enum MyIntegerLiteralEnum : Int {
    case One = 1
    case Two
    case Three
    case Four
}

print(MyIntegerLiteralEnum.One.sqrt)
print(MyIntegerLiteralEnum.Two.sqrt)
print(MyIntegerLiteralEnum.Four.sqrt)

/* 1.0
   1.4142135623731
   2.0               */

As a disclaimer, note that this extension will be made available to all types that conforms to RawRepresentable with a rawValue of type Int, not only enum types. E.g.:

struct Foo : RawRepresentable {

    typealias RawValue = Int
    var bar : Int

    var rawValue: RawValue {
        get {
            return bar
        }
    }

    init(rawValue bar: Int) {
        self.bar = bar
    }
}

var a = Foo(rawValue: 16)
print(a.sqrt) // 4.0
Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192