首页 > 解决方案 > 检查元类型,作为参数获取

问题描述

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
    }
}

这给出了编译错误:Expression pattern of type 'Vc1.Type' cannot match values of type 'UIViewController.Type'

尝试Any.Type而不是UIController.Type- 同样的错误。

什么是正确的语法?

标签: swiftfunction

解决方案


我想也许你的意图是实例化一个 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")

希望能帮助到你。


推荐阅读