【问题标题】:"Expression was too complex to be solved in reasonable time..." with hashValue“表达式太复杂,无法在合理的时间内解决......”与 hashValue
【发布时间】: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


【解决方案1】:

将你的表达式分成多个部分,并通过在下一个添加中追加来添加所有部分

var hashValue:Int
    {
        let firstFrg =  (31 &* id.hashValue)
                &+ projectID.hashValue
                &+ parentID.hashValue
                &+ name.hashValue
        let secondFrg = firstFrg + &+ description.hashValue
                &+ url.hashValue
                &+ (startOn != nil ? startOn!.hashValue: 0)
        let thirdFrg = secondFrg + &+ (startedOn != nil ? startedOn!.hashValue: 0)
                &+ (dueOn != nil ? dueOn!.hashValue: 0)
                &+ (completedOn != nil ? completedOn!.hashValue: 0)
        let fourthFrg = thirdFrg + &+ isStarted.hashValue
                &+ isCompleted.hashValue

         return fourthFrg
    }

【讨论】:

  • 好的,这就是编译器的想法!不完全优雅,但如果这是唯一的方法......
  • 在相关说明中......如果有许多更长的 Hashable 方法,有什么办法可以防止编译时间的疯狂增加?我的构建从 ~1 分钟到 ~10 分钟。
  • ... 另外,现在我有几个模型类使用分解的可散列方法实现,编译需要很长时间,然后失败并出现以下错误:Error:unable to execute command: Killed: 9, Error:compile command failed due to signal 9 (use -v to see invocation)
猜你喜欢
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
相关资源
最近更新 更多