简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM