gpt4 book ai didi

swift - 如何测试另一个快速通用类型?

转载 作者:搜寻专家 更新时间:2023-11-01 07:31:21 24 4
gpt4 key购买 nike

我有一些通用类型类,但没有要测试的对象实例。我想做的是根据运行时类型改变函数的行为。

class MyGenericUtility<SomeGenericClass> {

func myFunction() {
// so far I have tested "is", "==" and "==="
if SomeGenericClass is SomeRealClass {
println("some special stuff there")
}
println("some generic stuff as the name tells")
}

}

最佳答案

你可以比较类类型,使用 SomeGenericClass.self == SomeRealClass.self 作为,

class MyGenericUtility<SomeGenericClass> {
func myFunction() {
if SomeGenericClass.self == SomeRealClass.self {
print("SomeRealClass stuffs")
} else if SomeGenericClass.self == String.self {
print("String stuffs")
}
}
}


let someRealUtility = MyGenericUtility<SomeRealClass>()
someRealUtility.myFunction()

let stringUtility = MyGenericUtility<String>()
stringUtility.myFunction()

关于swift - 如何测试另一个快速通用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32385493/

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