Search code examples
javaswiftgenericsanyobject

Swift Generics equivalent of Java any type <?>


In Java you can some times use generics without caring about the actual type. Can you do that in Swift?

For instance MyClass<AnyObject> doesn't work like MyClass<?> would in Java. At I'd expect it to work the same.

Is there any other way?


Solution

  • Introduce a type parameter; the compiler will let it take any type. Try:

    func executeRequest<T> (request: APIRequest<T>) {
     // ...
    }
    

    For example:

    class APIRequest<T> {}
    class Movie {}
    class MovieRequest : APIRequest<Movie> {}
    let m = MovieRequest()
    //print(m)
    
    func executeRequest<T> (request: APIRequest<T>) {
        print(request)
    }
    
    executeRequest(m)
    

    The introduction of a type parameter allows one to be more explicit and to better match the problem domain. For example, in your case, you surely can't do a APIRequest on anything whatsoever; you can make an APIRequest on, say, a Resource.

    protocol Resource {}
    class Movie : Resource {}
    class Song : Resource {}
    
    class APIRequest<T:Resource> { /* ... */ }
    
    func executeRequest<T:Resource> (request: APIRequest<T>) { /* ... */ }