[Swift] Allow @required attribute on initializers in protocol

Originator:martijn
Number:rdar://17408284 Date Originated:06/21/2014
Status:Open Resolved:
Product:Developer Tools Product Version:
Classification:Enhancement Reproducible:
 
The @required attribute can be applied to a designated or convenience initializer of a class to indicate that every subclass must implement that initializer. Currently, it cannot be used in protocols, but I've come across a use case that I think would benefit from this.

I've previously filed a bug (#17358843) because UICollectionView does not define init(coder:) as a designated initializer, which means trying to define init(coder:) in a subclass leads to a 'Must call a designated initializer of the superclass' compiler error.

Having UICollectionView explicitly indicate conformance to NSCoding would help, but a better solution to avoid problems like this in the future might be to have the compiler treat it as an error if an initializer defined in an adopted protocol is not included. In this case, because UIView indicates conformance to NSCoding, that would mean all subclasses should either inherit (subject to the automatic initializer inheritance rules) or define init(coder:). It seems to me this is something the compiler should check for (as it does now for protocols adopted directly) because otherwise classes could implicitly conform to a protocol through their superclass yet not fulfill all the requirements:

class NonCodingView : UIView {
  init(frame: CGRect) {
    super.init(frame: frame)
  }
}

It seems to me allowing the @required attribute in protocols could help here. Applying this attribute to init(coder:) in NSCoding would force all subclasses to implement that initializer. The above code should therefore generate a compiler error to the effect that init(coder:) is required.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!