3

Is there a standard mechanism for annotating function declarations in Swift to indicate that they are present because a class conforms to some protocol?

For instance, this declaration might be present because a class conforms to NSCoding. (Marking it with override would result in a syntax error, so it's not the kind of annotation I am looking for.) Ideally I am looking for a code-level annotation (e.g. override instead of /*! ... */).

// ... annotation such as "conform to NSCoding", if possible
func encodeWithCoder(encoder: NSCoder) {
   // ...
}
Drux
  • 11,992
  • 13
  • 66
  • 116

1 Answers1

3

You can use extension. for example:

protocol SomeProtocol {
    func doIt() -> Int
}


class ConcreteClass {
    ....
}

extension ConcreteClass: SomeProtocol {
    func doIt() -> Int {
       // ...
       return 1
    }
}

But you cannot define required initializer in extension, for example:

// THIS DOES NOT WORK!!!

class Foo: NSObject {
}
extension Foo: NSCoding {
    required convenience init(coder aDecoder: NSCoder) {
        self.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ...
    }
}

emits an error:

error: 'required' initializer must be declared directly in class 'Foo' (not in an extension)
    required convenience init(coder aDecoder: NSCoder) {
    ~~~~~~~~             ^

In this case, you should use // MARK: comments:

class Foo: NSObject {

    // ...


    // MARK: NSCoding

    required init(coder aDecoder: NSCoder) {
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ... 
    }
}
Community
  • 1
  • 1
rintaro
  • 51,423
  • 14
  • 131
  • 139