Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I constrain a Swift protocol to a concrete type?

Tags:

generics

swift

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?

like image 439
Gregory Higley Avatar asked Jan 17 '15 02:01

Gregory Higley


People also ask

Is it possible to prevent the adoption of a protocol by a struct?

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.

Can we use protocol with structure in Swift?

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.

Can Swift protocols have properties?

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.

Can we create object of protocol Swift?

You can not create an instance of protocol. But however you can refer an object in your code using Protocol as the sole type.


1 Answers

Try:

class Stream<S: SequenceType where S.Generator.Element == Character> {
//                                                     ^^
    init(_ sequence: S) {}
}
like image 62
rintaro Avatar answered Sep 29 '22 18:09

rintaro