gpt4 book ai didi

Swift:约束泛型参数以用于更受约束的泛型函数

转载 作者:行者123 更新时间:2023-11-28 05:54:11 26 4
gpt4 key购买 nike

我正在实现一个类,它需要符合如下所示的协议(protocol):

protocol P {
func magic<T>(_ thing: Thing, as type: T.Type) -> T
}

这个协议(protocol)是由第三方代码提供的,这意味着我不能以任何方式改变它来解决这个问题。

现在,我有一个通用函数

func magicForObject<T: AnyObject>(_ thing: Thing, as type: T.Type) -> T

我想在我的magic 实现中调用它,只是为了输入thing,它们实际上是对象。也就是说,我想做这样的事情:

func magic<T>(_ thing: Thing, as type: T.Type) -> T {
if T.self is AnyClass {
return magicForObject(thing, as: type)
}
else {
// do something else
}
}

但我找不到任何方法来完成这项工作。上面的代码显然不能编译,像这样的东西也不能编译

if let T_ = T.self as? AnyClass { ... }

因为 T_ 只是一个普通变量,而不是一个通用参数(大概是编译时的)。

我也试过这样做:

func magic<T: AnyObject>(_ thing: Thing, as type: T.Type) -> T { ... }
func magic<T>(_ thing: Thing, as type: T.Type) -> T { ... }

并分别实现两者。如果直接在对象上调用此函数,则会正确调用受约束的 AnyObject,但当对象被转换为协议(protocol)类型 P 时,不会,在在这种情况下,总是使用第二种。

这种情况似乎无可救药地受到限制,但有没有我没有想到的解决方法?

更新

目前看来这在 Swift 中是不可能的。我做了一个post pitching the idea在 Swift 论坛中;如果您也需要这些,请随时提出意见。

最佳答案

你的例子有点难用,所以我不得不做很多假设,但我想这应该能满足你的要求。

根据你所说的,你有一个给定的协议(protocol) P:

protocol P {
func magic<T>(_ thing: Thing, as type: T.Type) -> T
}

让 P 为您提供您需要它执行的操作的默认实现:

extension P {
// Implementation for magic where T is a class
func magic<T>(_ thing: Thing, as type: T.Type) -> T where T: AnyObject {
print("AnyObject Called")
return Test2() as! T
}

// Implementation for magic where T is a struct
func magic<T>(_ thing: Thing, as type: T.Type) -> T {
print("Struct Called")
return Test() as! T
}
}

你有一个符合 P 的类

class Test2: P {

}

假设您有这个 Thing 对象和一个我们要传递的结构,看看我们是否有正确的结果:

class Thing {

}

struct Test {

}

现在让我们测试一下我们是否在 Test2 上调用 magic 它是否会根据传递给 type 调用正确的函数魔法

let test = Test()
let test2 = Test2()

// T is Test2 so its a class
test2.magic(Thing(), as: Test2.self)
// T is Test so its a struct
test2.magic(Thing(), as: Test.self)

打印输出调用

AnyObject Called
Struct Called

看起来你可以为 structs 做一些事情,为 classes 做另一件事

关于Swift:约束泛型参数以用于更受约束的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51953982/

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