枚举作为字典的键

时间:2019-06-14 17:31:17

标签: swift dictionary hash enums

我有字典

provider "aws" {
  region = "us-gov-west-1"
  access_key = "${var.aws_access_key}"
  secret_key = "${var.aws_secret_key}"
}

... Other VPC resources.

resource "aws_route53_zone" "private" {
  name = "my-domain.com"
  comment = "my-domain (preprod-gov) terraform"

  vpc = {
    vpc_id = "${module.preprod_gov_vpc.vpc_id}"
  }
}

我在这里使用枚举作为键,但是由于某些原因它不起作用,字典不会使用这些键创建任何对象。

var observers: [ObservingType: [MessageObserverManager?]] = .init()

请您告知枚举有什么问题?

guard观察者[.allMessages] ?. isEmpty?否则为假{         观察者[.allMessages] ?. append(观察者)

enum ObservingType: Hashable {
case messages(codeId: Int, codeTwoId: Int)
case allMessages
case threadMessages(otherId: Int)

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

func hash(into hasher: inout Hasher) {
    switch self {
    case .messages(let codeId, let codeTwoId):
        hasher.combine(codeId)
        hasher.combine(codeTwoId)
        hasher.combine(1000 / Int.random(in: 1...25))

    case .allMessages:
        hasher.combine(100000 / Int.random(in: 1...25))

    case .threadMessages(let otherId):
        hasher.combine(otherId)
        hasher.combine(100000000 / Int.random(in: 1...25))
    }
}

这是我用来添加值的代码,问题是我没有创建那些数组,所以原因不在枚举中,对不起,谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您对==的实现不正确。不要比较哈希值。比较实际值。请记住,两个不相等的值允许具有相同的哈希值。

您对hash的实现不应使用随机数。删除这些行。给定值的哈希值必须稳定(至少在应用程序的一次执行期间)。您无法在键的哈希字典中查找值不断变化。

在这种情况下,最简单的解决方案是让编译器生成==hash(into:)。然后您的代码将变为:

enum ObservingType: Hashable {
    case messages(codeId: Int, codeTwoId: Int)
    case allMessages
    case threadMessages(otherId: Int)
}

这要简单得多,您现在可以将enum用作字典的键。

相关问题