How to pass a Swift type as a method argument?

守給你的承諾、 提交于 2020-07-14 16:27:37

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/39448849/how-to-pass-a-swift-type-as-a-method-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!