有没有办法动态地将类型参数传递给通用的 swift 类?以下仅出于说明目的,来自一个给出错误的 Playground :使用未声明的类型“按钮”
import Cocoa
class PrintNameOfClass<T: NSObject> {
func printType() {
print(type(of: T.self))
}
}
let button = NSButton()
let test = PrintNameOfClass<button>()
test.printType()
最佳答案
在这种情况下,更合理的做法是使函数通用而不是类能够传递实例 按钮
class PrintNameOfClass {
func printNameOfClass<T : NSObject>(of : T) {
print(type(of: T.self))
}
}
let button = NSButton()
let test = PrintNameOfClass()
test.printNameOfClass(of: button)
关于swift - 通用类型参数作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57372385/