gpt4 book ai didi

swift - 协议(protocol)字典 Swift 4

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

我有一个名为 playable 的协议(protocol),它需要执行 func play()Damage类和DrawACard类都符合协议(protocol)

protocol Playable: class {
func play(game: Game, value: Int) -> Player
}


class Damage: Playable, Hashable, Equatable {

var hashValue: Int = 1

static func ==(lhs: Damage, rhs: Damage) -> Bool {
return lhs.hashValue == rhs.hashValue
}

func play(game: Game, value: Int) -> Player {
// do stuff
return game.activePlayer
}
}

class DrawACard: Playable, Equatable, Hashable {

var hashValue: Int = 2

static func ==(lhs: DrawACard, rhs: DrawACard) -> Bool {
return lhs.hashValue == rhs.hashValue
}

func play(game: Game, value: Int) -> Player {
// do stuff
return game.activePlayer
}
}

我的问题如下:

class Card {
var id: Int
var name: String
var cost: Int
var description: String
var target: Target
var abilities: [Playable: Int]
var cardType: CardType

init(id: Int, name: String, cost: Int, description: String, cardType: CardType, target: Target, abilities: [Playable: Int]) {
self.id = id
self.name = name
self.cost = cost
self.description = description
self.cardType = cardType
self.abilities = abilities
self.target = target
}
}

当我尝试将协议(protocol)作为键时,abilities 类中的第 6 个变量抛出错误。它给我:Type 'Playable' does not conform to protocol 'Hashable'

我希望 abilities 变量具有实现 Playable 的对象的键和 Int 的值,例如。 abilities = [DrawACard: 5]

我该怎么做呢?

Error

最佳答案

这种带有类继承的混合协议(protocol)非常复杂。你的具体问题的答案是你不能直接,因为如果你让 Playable 符合 Hashable,你就不能制作它们的数组。

最简单的解决方案是不要在此处使用协议(protocol)。只做一个抽象类。 Swift 不太擅长抽象类,但它们将使大多数这些问题消失。

鉴于您的具体情况,我可能还会考虑为 Playable 使用枚举而不是协议(protocol)。这可能会使事情变得更简单。

从那里开始,解决方案变得有点复杂。例如,您可以根据我的 ClassSet 创建一个 ClassDictionary实验。或者你可以构建一个类型橡皮擦。但它变得丑陋。

您还可以考虑从类切换到结构,摆脱字典,只使用数组。如果 Int 的点是一个计数,那么只需要该结构的多个副本。如果 Int 的点是一个参数(比如“多少伤害”),那么它应该在 Damage 结构中,而不是在字典中。

(不相关的说明,您的散列值非常奇怪。它们会起作用,但这不是散列的本意。)

作为我要去的地方的一个例子,我看到了类似的东西:

protocol Playable {
func play(game: Game) -> Player
}

struct Damage: Playable {
let amount: Int

func play(game: Game) -> Player {
// do stuff
return game.activePlayer
}
}

struct DrawACard: Playable {
func play(game: Game) -> Player {
// do stuff
return game.activePlayer
}
}

struct Card {
let id: Int
let name: String
let cost: Int
let description: String
let cardType: CardType
let target: Target
let abilities: [Playable]
}

// A card that inflicts one damage
let card = Card(id: 1,
name: "Strike",
cost: 1,
description: "Strike 'em",
cardType: CardType(),
target: Target(),
abilities: [Damage(amount: 1)])

这有意将所有内容切换为不可变结构;我相信您在这里描述的所有内容都是真正的值类型。

关于swift - 协议(protocol)字典 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479839/

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