Alex
Alex

Reputation: 1058

How to pass any class or struct as a parameter in function?

I am using Swift 4.1 and Xcode 9.3. I want to make a function which takes any Class or Struct as parameter.

Code example:

func cast<T>(a: Any, b: T) {

    let c = a as? b

    if let c = c {
        print("Good: \(c)")
    } else {
        print("Bad")
    }

}

cast(a: 1, b: Int.self)

But it has error in this line:

let c = a as? b

Error: Use of undeclared type 'b'

I want to call function cast like this: cast(a: 1, b: Int) or like this: cast(a: "a", b: String) The main idea to pass class or struct as parameter in generics functions correctly, how to do this? Thank you very much for any help or advice!

Upvotes: 2

Views: 1797

Answers (1)

Ivan Smetanin
Ivan Smetanin

Reputation: 2039

You should cast property to the type you've passed

let c = a as? T

And if you want to pass a type to the method you should write T.Type

Complete code:

func cast<T>(a: Any, b: T.Type) {

    let c = a as? T

    if let c = c {
        print("Good: \(c)")
    } else {
        print("Bad")
    }

}

Usage:

cast(a: 1, b: Int.self)
cast(a: "a", b: String.self)

After run these two lines you'll see in console:

Good: 1
Good: a

Upvotes: 4

Related Questions