检查元类型,作为参数获取

时间:2019-04-18 05:05:21

标签: swift function

类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-同样的错误。

正确的语法是什么?

2 个答案:

答案 0 :(得分:0)

我想您可能打算实例化一个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")

希望有帮助。

答案 1 :(得分:-2)

检查以下样品进行检查。它可能会帮助您。

string = string[-2:] + string[:-2]

它将显示“ C”