一个 Swift typealias 可以在协议定义中被约束到另一个吗?如果没有,我还能如何实现组件注册之类的东西?
Can one Swift typealias be constrained to another in a protocol definition? If not, how else can I achieve something like component registration?
我正在 swift 中为我自己的小框架编写一个小型的控制反转容器(主要是为了我可以了解更多信息)并且我偶然发现了一个问题 - 好吧,这只是其中的几个问题最新的。
我曾希望 swift 足够灵活,可以让我在 C# 中移植 Castle.Core
的核心模式。我的第一个失望是苹果提供的反射能力很弱,导致我做了这个丑事...
public protocol ISupportInjection {
}
public protocol IConstructorArguments {
func toArgumentsDictionary() -> [String:AnyObject?]
}
public protocol ISupportConstructorInjection: ISupportInjection {
init(parameters:IConstructorArguments)
}
...我的想法是有一天(很快)我可以处理它并在我的 services/components.
中删除对这些约束的任何引用
现在我想用两个 typealias
写 IIocRegistration
:一个用于 TService
,另一个用于 TComponent
,理想情况下 TService
是protocol
和 TComponent
是实现 TService
:
的具体 struct
或 class
public protocol IIocRegistration {
typealias TService: Any
typealias TComponent: TService, ISupportConstructorInjection
}
但是根据编译器看来 TComponent: TService
是完全无效的,它说:
Inheritance from non-protocol, non-class type '`Self`.TService'
所以我想知道如何使 typealias
派生另一个 typealias
如果可能的话。
首先,typealias
在 swift 协议中做的不是定义类型别名。 swift 协议中的关键字 typealias
用于定义 associated type
,你可以查看 swift 编程书籍。
回到你的情况,我能想出的可能解决方案是像这样移动 typealias
外部协议
public typealias TService = Any
public struct component: TService, ISupportConstructorInjection {
public init(parameters: IConstructorArguments) {
//
}
}
public typealias TComponent = component
public protocol IIocRegistration {
var service: TService {get set}
var component: TComponent {get set}
}
我正在 swift 中为我自己的小框架编写一个小型的控制反转容器(主要是为了我可以了解更多信息)并且我偶然发现了一个问题 - 好吧,这只是其中的几个问题最新的。
我曾希望 swift 足够灵活,可以让我在 C# 中移植 Castle.Core
的核心模式。我的第一个失望是苹果提供的反射能力很弱,导致我做了这个丑事...
public protocol ISupportInjection {
}
public protocol IConstructorArguments {
func toArgumentsDictionary() -> [String:AnyObject?]
}
public protocol ISupportConstructorInjection: ISupportInjection {
init(parameters:IConstructorArguments)
}
...我的想法是有一天(很快)我可以处理它并在我的 services/components.
中删除对这些约束的任何引用现在我想用两个 typealias
写 IIocRegistration
:一个用于 TService
,另一个用于 TComponent
,理想情况下 TService
是protocol
和 TComponent
是实现 TService
:
struct
或 class
public protocol IIocRegistration {
typealias TService: Any
typealias TComponent: TService, ISupportConstructorInjection
}
但是根据编译器看来 TComponent: TService
是完全无效的,它说:
Inheritance from non-protocol, non-class type '`Self`.TService'
所以我想知道如何使 typealias
派生另一个 typealias
如果可能的话。
首先,typealias
在 swift 协议中做的不是定义类型别名。 swift 协议中的关键字 typealias
用于定义 associated type
,你可以查看 swift 编程书籍。
回到你的情况,我能想出的可能解决方案是像这样移动 typealias
外部协议
public typealias TService = Any
public struct component: TService, ISupportConstructorInjection {
public init(parameters: IConstructorArguments) {
//
}
}
public typealias TComponent = component
public protocol IIocRegistration {
var service: TService {get set}
var component: TComponent {get set}
}