Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotating Swift function declarations that support conformance to a protocol?

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) {
   // ...
}
like image 759
Drux Avatar asked Feb 11 '26 10:02

Drux


1 Answers

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) {
        // ... 
    }
}
like image 197
rintaro Avatar answered Feb 15 '26 12:02

rintaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!