Why can I make the same requirement in swift with generics? Is there anyway?

So, I have a class defined as follows:

public final class Process<InputType, OutputType, Memory> 

And I want the function to be available only when InputType and Type OutputType are of the same type. So I tried like this:

 extension Process where InputType == OutputType { } 

But this will result in:

The requirement for one type creates the common parameters InputType and OutputType equivalent

So, I left a little and tried to do it like this:

 func bypass<SameType>() -> Process<SameType, SameType, Memory> where OutputType == InputType {} 

But this will lead to exactly the same error. So the question is why I cannot define generics in such a way that the two typical types would be equivalent, because that's exactly what I wanted. I would like to define a function available only for this case, which did not work during compilation, if this rule is not respected.

So now I am using something like this:

 public static func bypass<SameType>() -> Process<SameType, SameType, Memory> 

Which ultimately will fail only at runtime and even at creation, but when a particular class is launched for action.

Is it possible to define extension or function for common parameters of the same type that simply will not compile (result of a compile-time error)?

Update: some implementation information is missing, which will make the code unreadable, and they are not critical for the context

+5
source share
1 answer

In Swift 4 and later, you can write:

 public final class Process<InputType, OutputType, Memory> { // ... } extension Process where InputType == OutputType { func bypass() -> Process<InputType, OutputType, Memory> { // ... } } 

Original answer (Swift 3):

You cannot restrict types to general classes, although some changes are included in Swift 4. However, you can restrict types to protocol. You can make a protocol that only matches Process as follows:

 protocol ProcessProtocol { // I haven't found a way to name these associated type identically to // those in the class. If anyone discover a way, please let me know associatedtype IT associatedtype OT associatedtype MT } final public class Process<InputType, OutputType, MemoryType>: ProcessProtocol { typealias IT = InputType typealias OT = OutputType typealias MT = MemoryType // your code } // Note that this is an extension on the protocol, not the class extension ProcessProtocol where IT == OT { func foo() { // this function is only available when InputType = OutputType } } 
+6
source

Source: https://habr.com/ru/post/1260738/


All Articles