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) {
   // ...
}
4
  • Annotating in a comment, or in the code? Commented Aug 20, 2015 at 7:30
  • @Aderstedt Annotating in the code would be best (see update to Q). Commented Aug 20, 2015 at 7:38
  • AFAIK there's no way to annotate protocol conformance in the code. Use comments. Commented Aug 20, 2015 at 7:51
  • @robertvojta Too bad. (I am using comments now but wish for an alternative.) Commented Aug 20, 2015 at 7:56

1 Answer 1

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) {
        // ... 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.