swiftgenericstype-alias

Simplified typealias for generic swift types


I have a Cache implementation that looks like this:

class Cache<Key: Hashable, Value> {}

It's mostly (but not always) used to cache Identifiable things, and my instantiation often looks like:

struct User: Identifiable { var id: String }

var userCache = Cache<User.ID, User>()

I'm curious whether it's possible to write a typealias or other definition that provides syntactic sugar and allows an instantiation like:

var userCache = Cache<User>()

where I can then use Value.ID internally as the Key.

I've tried a typealias:

typealias Cache<Value: Identifiable> = Cache<Key = Value.ID, Value> // (Syntax error)

and a second class definition:

class Cache<Value: Identifiable> {}

class Cache<Key: Hashable, Value> {} // (Invalid redeclaration)

I want to retain the flexibility of the basic definition, to also cache things that are not Identifiable. Is this possible in Swift?


Solution

  • You can use a generic typealias, but it needs to have a different name:

    typealias IdentityCache<T: Identifiable> = Cache<T.ID, T>
    

    You can't overload generic types with different numbers of arguments, like you could with functions