Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic in subscript for swift

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

like image 982
Alex Zielenski Avatar asked Oct 07 '14 04:10

Alex Zielenski


People also ask

How do you subscript in Swift?

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...

What is generic type in Swift?

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.

What is multidimensional subscript in Swift?

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.


2 Answers

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
like image 142
Mike S Avatar answered Oct 21 '22 18:10

Mike S


Generic subscripts are now available in Swift 4: SE-0148

like image 23
Joe Avatar answered Oct 21 '22 18:10

Joe