Mathijs Segers Mathijs Segers - 3 months ago 8
Swift Question

Swift: Check has a protocol and use getter Like you would in Java

I was wondering if it is possible to check if a class conforms to a protocol in swift.

I have an EntityObject class, which contains some basic functionality in Java I'd make it abstract but since swift doesn't do abstraction I'm running it like this.

I also have an Entity Protocol which requires a getter for a path property (which does not really exist but always returns the path in our API).

Now in the EntityObject class which is always extended (otherwise you get fatalError's in your face). I want to get this path but EntityObject does not conform to the Entity Protocol but it's children do in most cases.

example path getter:

class var path:String {get { return "blog/{blogId}/comments" } }

The getters do not show up in the Mirror using reflect() probably because it's a class(static) var, and I tried something like:

if let entity = self as? Entity {
return entity.path

But this returns an instance of Entity (I guess) since I'm not allowed to use the path here or see any of the options.

Anyone know if I could do this generically?


Since the property I wanted to invoke was not an instance, but a Type property I couldn't get it from the instance, the dynamicType property does however let me. So in my case it would be.

    if let path = self.dynamicType.valueForKey("path") as? String {
        return path

This will fetch the path var as string if it is there. Making my entire function:

func getPath() -> String? {
    if let path = self.dynamicType.valueForKey("path") as? String {
        return path

    ErrorClass.log("Path not implemented on \(self), does not inherit from entity?")
    return nil