具有通用类型的专用协议

问题描述 投票:0回答:1

我遇到协议和泛型类型之间的问题

我有这个

Container
协议

protocol Container {
    associatedtype State : Any
    associatedtype Effect : Any
    associatedtype Intent : Any
    
    var store: Store { get }
}

还有这个协议

Store

protocol Store {
    associatedtype State : Any
    associatedtype Effect : Any

    var state: AnyPublisher<State, Never> { get }
    var effect: AnyPublisher<Effect, Never> { get }
}

我希望

store
中的
Container
是 Store 类型,其中 State 和 Effect 与 Container 协议中指定的相同。但我不明白如何,编译器要求我使用
any Store
但它会删除输入。

而且,对于

any
,如果我尝试在
state
出版商上订阅,我会收到错误:
Member 'state' cannot be used on value of type 'any Store'; consider using a generic constraint instead

我尝试这样做

protocol Container {
    associatedtype State : Any
    associatedtype Effect : Any
    associatedtype Intent : Any
    
    var store: Store<State, Effect> { get }
    
    func post(intent: Intent)
}

但是编译器再次抱怨

Protocol 'Store' does not have primary associated types that can be constrained

我真的不明白如何实现我想要的。

抱歉,如果这是一个基本问题,我本来就是一名 Kotlin 开发人员。需要明确的是,在 Kotlin 中,如果有帮助的话那就是这个:

interface Container<State : Any, Effect : Any, Intent : Any> {
    val store: Store<State, Effect>

    fun post(intent: Intent)
}

希望有人能帮助我!谢谢

swift generics swift-protocols
1个回答
0
投票

正如错误消息之一所述,您可以将主要关联类型添加到

Store
以使
Store<State, Effect>
成为可能。

protocol Store<State, Effect> {
    associatedtype State
    associatedtype Effect

    var state: AnyPublisher<State, Never> { get }
    var effect: AnyPublisher<Effect, Never> { get }
}

protocol Container {
    associatedtype State
    associatedtype Effect
    associatedtype Intent
    
    var store: any Store<State, Effect> { get }
    
    func post(intent: Intent)
}

现在可以订阅

state
/
effect
:

func foo<T: Container>(container: T) {
    container.store.effect.sink { effect in
        // ...
    }
}

您似乎正在将用 Kotlin 编写的内容“逐字逐句”翻译成 Swift。对于编程语言和自然语言来说,这都不是一个好主意。 Kotlin

interface
和 Swift
protocol
具有非常不同的语义和功能。是的,它们都声明了实现类型的要求,但这就是相似之处。您稍后可能会遇到问题。

与 Kotlin 中的

: Any
约束强制类型参数不可为空不同,Swift 中的
: Any
是多余的。 Swift 中的
SomeType?
(又名
Optional<SomeType>
)可能“看起来像”Kotlin 意义上的可空类型,但它具有非常不同的语义。通常没有充分的理由将类型参数限制为非
Optional

© www.soinside.com 2019 - 2024. All rights reserved.