Collections of Protocol Types - 面向协议的编程
Collections of Protocol Types - protocol oriented programming
我想要一个协议类型的集合:在这种情况下,我想要一个变量“party”是一个 GameCharacter 类型的数组,这样我就可以把所有符合GameCharacter 里面。
下面的代码会产生以下错误:
Protocol 'GameCharacter' can only be used as a generic constraint because
it has Self or associated type requirements
这里有什么问题?怎么做才对?
protocol GameCharacter: Identifiable {
var name: String {get}
var maxHealt: Int {get}
var healt: Int { get set }
}
struct Warrior: GameCharacter, Fighter {
var name: String
var maxHealt: Int
var healt: Int
var armor: Armor
var weapon: Weapon
var resistence: Int
var id: String {
return name
}
}
var party: [GameCharacter] <--- error
在这种情况下,您不应该从 Identifiable
(具有泛型)继承您的协议,而是显式添加 id
然后下面(简化)是可编译的
protocol GameCharacter {
var id: String { get } // << here !!
var name: String {get}
var maxHealt: Int {get}
var healt: Int { get set }
}
struct Warrior: GameCharacter {
var name: String
var maxHealt: Int
var healt: Int
var resistence: Int
var id: String { // << here !!
return name
}
}
我相信Identifiable
是一个关联类型的协议。不幸的是,Swift 不支持您想要实现的目标,还。
有关此主题的讨论,请参阅 Swift associated types and protocol inheritance and How to use generic protocol as a variable type。这些链接也讨论了可能的解决方案。
我想要一个协议类型的集合:在这种情况下,我想要一个变量“party”是一个 GameCharacter 类型的数组,这样我就可以把所有符合GameCharacter 里面。
下面的代码会产生以下错误:
Protocol 'GameCharacter' can only be used as a generic constraint because it has Self or associated type requirements
这里有什么问题?怎么做才对?
protocol GameCharacter: Identifiable {
var name: String {get}
var maxHealt: Int {get}
var healt: Int { get set }
}
struct Warrior: GameCharacter, Fighter {
var name: String
var maxHealt: Int
var healt: Int
var armor: Armor
var weapon: Weapon
var resistence: Int
var id: String {
return name
}
}
var party: [GameCharacter] <--- error
在这种情况下,您不应该从 Identifiable
(具有泛型)继承您的协议,而是显式添加 id
然后下面(简化)是可编译的
protocol GameCharacter {
var id: String { get } // << here !!
var name: String {get}
var maxHealt: Int {get}
var healt: Int { get set }
}
struct Warrior: GameCharacter {
var name: String
var maxHealt: Int
var healt: Int
var resistence: Int
var id: String { // << here !!
return name
}
}
我相信Identifiable
是一个关联类型的协议。不幸的是,Swift 不支持您想要实现的目标,还。
有关此主题的讨论,请参阅 Swift associated types and protocol inheritance and How to use generic protocol as a variable type。这些链接也讨论了可能的解决方案。