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
To access elements via subscripts write one or more values between square brackets after the instance name. For example: Array elements are accessed with the help of someArray[index] and its subsequent member elements in a Dictionary instance can be accessed as someDicitonary[key]. print(array[1... 4]) // 1...
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
While the most common subscripts are the ones that take a single parameter, subscripts are not limited to single parameters. Subscripts can take any number of input parameters and these parameters can be of any type.
You can't define a subscript
as 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 subscript
takes a type T
and returns a type U
. That would look something like:
class SomeClass<T, U> {
subscript(someParameter: T) -> U {
/* something that returns U */
}
}
For example, you could create a Converter
class that used the subscript
function to convert from type T
to type U
:
Note: This is a very contrived example, I wouldn't normally do this this way.
class Converter<T, U> {
var _converter: (T -> U)
init(converter: (T -> U)) {
_converter = converter
}
subscript(input: T) -> U {
let output = _converter(input)
return output
}
}
var convert = Converter(converter: {
(input: Int) -> String in
return "The number is: \(input)"
})
let s = convert[1]
println(s) // The number is: 1
Generic subscripts are now available in Swift 4: SE-0148
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With