swift - 检查元类型,作为参数获取
问题描述
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
- 同样的错误。
什么是正确的语法?
解决方案
我想也许你的意图是实例化一个 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")
希望能帮助到你。
推荐阅读
- java - 如何使用 SNMP 从 UPS 设备获取和设置值?
- javascript - MongoDB返回错误的行
- python - 如何使用 python 烧瓶 API 验证客户端
- c++ - 为什么我不能使用 const 指定的元素类型对对进行排序?
- php - 从 laravel 中的 hasManyThrough 关系中获取 id
- android - Flutter Android 无法构建 - Gradle 任务 assembleDebug 失败,退出代码为 1
- firebase - 如何使用本机图像的url删除firebase存储中的图像?
- version - 带有 runOnChange:true 版本 3.8 的 Liquibase sql 文件出现问题
- ios - IOS 13 + Left Swipe 不适用于以前的视图
- c - 如何只读取文件的第一个值,然后转到下一行?