ios – 采用Metatype的Swift函数?

正如苹果在 Swift的文档中的 Metatype Type部分中所说:

A Metatype type refers to the type of any type,including class types,structure types,enumeration types,and protocol types.

是否有一个基类来引用任何类,结构,枚举或协议(例如MetaType)?

我的理解是协议类型仅限于用作通用约束,因为Self或相关类型要求(嗯,这是Xcode错误告诉我的).

那么,考虑到这一点,也许有一个Class基类来识别类引用?或者是所有可构造类型(类,枚举)的Type基类?其他可能性可能是Protocol,Struct,Enum和Closure.

如果你没有明白我的意思,请看这个例子.

func funcWithType (type: Type) {
  // I Could store this Type reference in an ivar,// as an associated type on a per-instance level.
  // (if this func was in a class,of course)
  self.instanceType = type
}

funcWithType(String.self)
funcWithType(CGRect.self)

虽然泛型在1-2个常量关联类型中运行良好,但我不介意能够将关联类型视为实例变量.

谢谢你的建议!

解决方法

这有效:
func funcWithType (type: Any.Type) {
}

funcWithType(String.self)
funcWithType(CGRect.self)

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...