简体   繁体   English

Swift Enum的自定义类型符合hashable协议

[英]Swift Enum of custom types conform to hashable protocol

I have an enum like this: 我有这样的枚举:

enum Animals {
    case Cow     (MyCowClass)
    case Bird    (MyBirdClass)
    case Pig     (MyPigClass)
    case Chicken (MyChickenClass)
}

Each of the types conform to the hashable protocol. 每种类型都符合可混合协议。 This enum then becomes a property of a different class: 这个枚举然后成为另一个类的属性:

class Farm {
    let name = "Bob's Farm"
    var animal = Animals

    required init(animal: Animals) {
        self.animal = animal
    }

I would like to get the hash value from the instance of the case and use that for the enum so I can make the Farm class hashable using the name & animal. 我想从案例的实例中获取哈希值并将其用于枚举,这样我就可以使用名称&animal使Farm类可哈希。

You might make Animals hashable, eg: 你可以让Animals洗,例如:

enum Animals : Hashable {
    case Cow     (MyCowClass)
    case Bird    (MyBirdClass)
    case Pig     (MyPigClass)
    case Chicken (MyChickenClass)

    var hashValue: Int  {
        switch self {
        case .Cow(let v): return v.hashValue
        case .Bird(let v): return v.hashValue
        case .Pig(let v): return v.hashValue
        case .Chicken(let v): return v.hashValue
        }
    }
}
func ==(lhs: Animals, rhs: Animals) -> Bool {
    return ...
}

And likewise for class Farm , eg: 同样对于Farm类,例如:

class Farm : Hashable  {

    var hashValue: Int {
        return [name.hashValue, animal.hashValue].hashValue
    }
}
func ==(lhs: Farm, rhs: Farm) -> Bool {
    return ...
}

And finally, a container of Ints implements a property hashValue 最后,Ints的容器实现了一个属性hashValue

extension CollectionType where Generator.Element: Int {
    var hashValue: Int {
        return ...
    }
}

For appropriate algorithms, you may search the web - for example: http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx 对于适当的算法,您可以搜索网络 - 例如: http//www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx

An alternative to the accepted answer, assuming you don't want your enum based on the associated object is the following: 假设您不希望基于关联对象的枚举,则接受答案的替代方法如下:

private enum AnimalType: Int {
    case Cow = 0
    case Bird = 1
    case Pig = 2
    case Chicken = 3
}

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

enum Animals: Hashable {
    case Cow     (MyCowClass)
    case Bird    (MyBirdClass)
    case Pig     (MyPigClass)
    case Chicken (MyChickenClass)

    var hashValue: Int {
        get {
            switch self {
            case .Cow(_):
                return AnimalType.Cow.hashValue
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM