gpt4 book ai didi

Swift 比较两个元类型?

转载 作者:行者123 更新时间:2023-11-30 10:19:43 25 4
gpt4 key购买 nike

我需要测试我传递给函数的类型是否属于某个类

func doSomething<T> (type: T.Type) -> T {

// Check to see if type is the same as Raw type?

if type == Raw.self { } // Doesn't work, Compile error

if type is? Raw.self { } // Doesn't work, Compile error
}

@objc class Raw {

}

最佳答案

函数重载将是我的第一选择,但要回答这个问题;使用 NSStringFromClass 或以下内容:

@objc class Raw {

}

func doSomething<T: AnyObject> (type: T.Type) -> T {

type as AnyClass === Raw.self as AnyClass { }

// return something
}

这个解决方案似乎也适用于纯 Swift 类。

关于Swift 比较两个元类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com