Take a look at the following hypothetical code:
class Stream<S: SequenceType where S.Generator.Element: Character> {
init(_ sequence: S) {}
}
Doesn't compile. I get "S.Generator.Element constrained to non-protocol type Character". This is a bummer, man. I've thought of two possibilities:
class Stream<S: SequenceType where S.Generator.Element: ExtendedGraphemeClusterLiteralType> {
}
This constraint works because Character
is the only thing I know of to implement that protocol. The problem is that now I have an ExtendedGraphemeClusterLiteralType
instead of a Character
so I'm forced to cast, which I can live with.
The other possibility is just to define my own protocol, e.g., CharacterType
, and have Character
implement that through an extension. (This is probably also safer.) This is likely the approach I will actually take, but I wondered if anyone knew a way around this limitation other than this one?
The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. But there would be a time when you want to restrict protocols to be adopted by a specific class. In Swift 5, you can do just that.
In Swift, protocols contain multiple abstract members. Classes, structs and enums can conform to multiple protocols and the conformance relationship can be established retroactively. All that enables some designs that aren't easily expressible in Swift using subclassing.
A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn't specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.
You can not create an instance of protocol. But however you can refer an object in your code using Protocol as the sole type.
Try:
class Stream<S: SequenceType where S.Generator.Element == Character> {
// ^^
init(_ sequence: S) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With