Swift 正在检查作为参数获取的元类型

Swift 正在检查作为参数获取的元类型,swift,function,Swift,Function,类Vc1和Vc2是UIViewController的子类: class Vc1: UIViewController { .... } class Vc2: UIViewController { .... } 以下函数检查作为参数获取的发送方类型: func onVCComplete(senderType: UIViewController.Type, details: Any) { switch senderType { case Vc1.self: ...

类Vc1和Vc2是UIViewController的子类:

class Vc1: UIViewController { .... }
class Vc2: UIViewController { .... }
以下函数检查作为参数获取的发送方类型:

func onVCComplete(senderType: UIViewController.Type, details: Any) {

    switch senderType {
        case Vc1.self: ...            
        case Vc2.self: ...
        default: break
    }
}
这导致编译错误:
类型为“Vc1.type”的表达式模式与类型为“UIViewController.type”的值不匹配。

尝试了
Any.Type
而不是
UIController.Type
-相同错误


正确的语法是什么?

检查下面的示例以进行检查。这可能对你有帮助

class A {

}

class B : A {

}

class C : A {

}

func onVCComplete(senderType: A, details: Any) {

    if senderType is B {
        print("B")
    }
    if senderType is C {
         print("C")
    }
}

onVCComplete(senderType: C(), details: "A")


它将打印“C”

我想你的目的可能是实例化一个vc,检查它的实际类型,并对它做一些额外的工作……如果是这样,为什么不创建对象,然后检查它的类型呢

import UIKit

class Vc1: UIViewController {}

class Vc2: UIViewController {}

func onVCComplete<T: UIViewController>(senderType: T.Type, details: Any) {

    let vc = senderType.init()

    switch vc {
    case is Vc1:
        print("do something with Vc1")
    case is Vc2:
        print("do something with Vc2")
    default:
        print("some other vcs")
    }
}

onVCComplete(senderType: Vc1.self, details: "Whatever")

导入UIKit
类Vc1:UIViewController{}
类Vc2:UIViewController{}
func onVCComplete(发件人类型:T.类型,详细信息:任意){
设vc=senderType.init()
开关vc{
案例为Vc1:
打印(“用Vc1做点什么”)
案例是Vc2:
打印(“用Vc2做点什么”)
违约:
打印(“其他一些风投”)
}
}
onVCComplete(发送人类型:Vc1.self,详细信息:“任意”)

希望能有帮助。

这只是另一种类型,所以这就是为什么会出现错误。您可以将UIViewController发送到您的函数,并检查将其强制转换到特定子类是否成功。这似乎很奇怪,但如果您使用
if senderType==Vc1.self{}
,它不会抛出错误。我认为初始化ViewController只是为了检查其类型是不好的。但重点是通过元类型检查,而不是通过初始化