【发布时间】:2018-04-06 06:48:15
【问题描述】:
试图使我的整个数据模型可散列,例如....
let id:Int
let projectID:Int
let parentID:Int
let name:String
let description:String
let url:String
let startOn:Date?
let startedOn:Date?
let dueOn:Date?
let completedOn:Date?
let isStarted:Bool
let isCompleted:Bool
var hashValue:Int
{
return (31 &* id.hashValue)
&+ projectID.hashValue
&+ parentID.hashValue
&+ name.hashValue
&+ description.hashValue
&+ url.hashValue
&+ (startOn != nil ? startOn!.hashValue: 0)
&+ (startedOn != nil ? startedOn!.hashValue: 0)
&+ (dueOn != nil ? dueOn!.hashValue: 0)
&+ (completedOn != nil ? completedOn!.hashValue: 0)
&+ isStarted.hashValue
&+ isCompleted.hashValue
}
我得到编译错误:
错误:(112, 5) 表达式太复杂,无法合理解决 时间;考虑将表达式分解为不同的 子表达式
因此问题是:在哈希取决于许多属性的情况下,如何使对象成为可哈希对象?我有一些模型对象的数量是上述属性的 3-4 倍。
【问题讨论】:
-
您是否尝试过编译器的建议,即将表达式分解为不同的子表达式?
-
注意
(startOn != nil ? startOn!.hashValue: 0)可以更优雅地表达为(startOn?.hashValue ?? 0) -
顺便说一句:如果您将
Date?属性设为非可选,那么在 Swift 4.1 中,编译器 可以为您自动生成哈希函数,请参阅github.com/apple/swift-evolution/blob/master/proposals/…。
标签: swift hash compiler-errors