Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are where clauses only valid on functions with generic parameters?

Tags:

generics

swift

It seems absurd that this method signature does not compile in Swift 4:

class Bar<ValueType> { 
    func version() throws -> String where ValueType == [String: Any] { ... }
}   

(Error: where clause cannot be attached to a non-generic declaration)
but this compiles fine:

class Bar<ValueType> { 
   func version<T>(_ foo: T? = nil) throws -> String where ValueType == [String: Any] { ... }  
} 

Anyone have insight as to why this is the case?

like image 801
Sid Mani Avatar asked Aug 14 '17 17:08

Sid Mani


People also ask

Where clauses are declared for defining requirements for associated types?

Generic Where Clauses It can also be useful to define requirements for associated types. You do this by defining a generic where clause. A generic where clause enables you to require that an associated type must conform to a certain protocol, or that certain type parameters and associated types must be the same.

What is meant by generic function?

Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.

What is a generic type parameter?

Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.


1 Answers

Because ValueType has nothing to do with this method (in the first example). It would be wrong to put such a method in a type (class/struct/enum), since it's not really a true member of that type. It's conditionally a member of that type, depending on the truth value of the where clause.

To achieve this, you would want to put this method in an extension of your type, with the where clause you want. E.g.

extension YourType where ValueType == [String: Any] {
    func version() throws -> String { ... }
}
like image 111
Alexander Avatar answered Nov 15 '22 05:11

Alexander