Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 包含结构的数组的哈希值_Ios_Arrays_Swift_Hash - Fatal编程技术网

Ios 包含结构的数组的哈希值

Ios 包含结构的数组的哈希值,ios,arrays,swift,hash,Ios,Arrays,Swift,Hash,我有一个名为调查的结构。它同时符合equalable和Hashable协议 import Foundation public struct Survey { public let id: String public let createdAt: Date public let updatedAt: Date public let title: String public let type: String } extension Survey: Equa

我有一个名为调查的结构。它同时符合
equalable
Hashable
协议

import Foundation

public struct Survey {
    public let id: String
    public let createdAt: Date
    public let updatedAt: Date
    public let title: String
    public let type: String
}

extension Survey: Equatable { }

public func ==(lhs: Survey, rhs: Survey) -> Bool {
    return lhs.id == rhs.id && lhs.createdAt == rhs.createdAt && lhs.updatedAt == rhs.updatedAt && lhs.title == rhs.title && lhs.type == rhs.type
}

extension Survey: Hashable {
    public var hashValue: Int {
        return id.hashValue ^ createdAt.hashValue ^ updatedAt.hashValue ^ title.hashValue ^ type.hashValue
    }
}
我可以获得单个
Survey
对象的哈希值


但是如何获取包含多个
调查
对象的数组的哈希值呢?

可能是这样的

extension Array: Hashable where Iterator.Element: Hashable {
    public var hashValue: Int {
        return self.reduce(1, { $0.hashValue ^ $1.hashValue })
    }
}
自定义哈希值只是您定义的值

*编辑:如果您只希望
Survey
array的
Hashable
,这也可以使用

extension Array: Hashable where Element == Survey {
    public var hashValue: Int {
        return self.reduce(1, { $0.hashValue ^ $1.hashValue })
    }
}

首先,您可以简单地执行
public struct Survey:Hashable
,并去除所有其他内容(当然结构变量除外)。合成数组的Hashable一致性在Swift 4.2中实现:其次,
获取包含多个测量对象的数组的哈希值是什么意思。包括您希望为此实现的预期代码。类似于
[survey\u 1,survey\N].hashValue
?@staticVoidMan是的,没错。@Isuru然后介绍了Swift 4.1。实际上,您可以将其简化为
扩展数组,其中Element:Hashable
@staticVoidMan我认为OP希望对
数组
执行一些必须符合
Hashable
(比如使用
sensorderedset
),所以我认为保持注意是好的!我的坏:)扩展
Array
以明确地符合
Hashable
,并适当地使用where条件。