I understand that with Swift you can specify a function-specific generic with this form:
func someFunction<T>(type: T.Type) {...}
However, is it possible to do something similar with subscripts? Where you can specify a type within the brackets like so:
subscript<T>(type: T.Type) -> T {...}
EDIT: Updated solution based upon the accepted answer
subscript(type: AnyClass.Type) -> Any {
return sizeof(type)
}
EDIT 2: Upon testing, It seems that I cannot actually use this subscript. I get "CLASS is not identical to AnyClass.Type" so I am back to square one
You can't define a
subscriptas a generic function, but you can use a generic type if it's declared at the class level.For instance, lets say you want to make a class where the
subscripttakes a typeTand returns a typeU. That would look something like:For example, you could create a
Converterclass that used thesubscriptfunction to convert from typeTto typeU:Note: This is a very contrived example, I wouldn't normally do this this way.