Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Swift type as a method argument?

I'd like to do something like this:

func doSomething(a: AnyObject, myType: ????) {    if let a = a as? myType    {        //…    } } 

In Objective-C the class of class was Class

like image 834
juhan_h Avatar asked Sep 12 '16 11:09

juhan_h


People also ask

How do you pass an argument in Swift?

To pass function as parameter to another function in Swift, declare the parameter to receive a function with specific parameters and return type. The syntax to declare the parameter that can accept a function is same as that of declaring a variable to store a function.

What is type parameter in Swift?

A type parameter is simply the name of a placeholder type (for example, T , U , V , Key , Value , and so on). You have access to the type parameters (and any of their associated types) in the rest of the type, function, or initializer declaration, including in the signature of the function or initializer.

What is Inout in Swift?

Swift inout parameter is a parameter that can be changed inside the function where it's passed into. To accept inout parameters, use the inout keyword in front of an argument. To pass a variable as an inout parameter, use the & operator in front of the parameter.

How do I call a generic method in Swift?

Solution. A generic function that you might need to use explicit specialization is the one that infer its type from return type—the workaround for this by adding a parameter of type T as a way to inject type explicitly. In other words, we make it infer from method's parameters instead.


1 Answers

You have to use a generic function where the parameter is only used for type information so you cast it to T:

func doSomething<T>(_ a: Any, myType: T.Type) {     if let a = a as? T {         //…     } }  // usage doSomething("Hello World", myType: String.self) 

Using an initializer of the type T

You don’t know the signature of T in general because T can be any type. So you have to specify the signature in a protocol.

For example:

protocol IntInitializable {     init(value: Int) } 

With this protocol you could then write

func numberFactory<T: IntInitializable>(value: Int, numberType: T.Type) -> T {     return T.init(value: value) }  // usage numberFactory(value: 4, numberType: MyNumber.self) 
like image 73
Qbyte Avatar answered Oct 11 '22 04:10

Qbyte