gpt4 book ai didi

swift - 是否可以在 Swift 中构建嵌入式泛型?

转载 作者:行者123 更新时间:2023-11-28 06:37:22 28 4
gpt4 key购买 nike

假设我有一个这样的协议(protocol)和结构:

protocol A {
var someType: UnrelatedProtocol.Type { get }
}

struct B<T: UnrelatedProtocol> {
var anotherThing: T?
}

我想像这样一起使用它们:

struct C<T: A> {
typealias SomeThing = (B<T.someType>) -> Void
}

这在 Swift 中可能吗?我一直在玩这个,但不能完全正确。也许这是不可能的,但我觉得我应该能够做这样的事情。

谢谢!

最佳答案

首先我们有

protocol UnrelatedProtocol { }

现在我们需要在协议(protocol) A

中定义一个关联类型
protocol A {
associatedtype SomeType: UnrelatedProtocol
var someType: SomeType { get }
}

最后

struct B<T: UnrelatedProtocol> {
var anotherThing: T?
}

struct C<T: A> {
typealias Logic = (B<T.SomeType>) -> ()
}

关于swift - 是否可以在 Swift 中构建嵌入式泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839404/

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