【问题标题】:How to implement Hashable struct for Image in Swift如何在 Swift 中为 Image 实现 Hashable 结构
【发布时间】:2020-03-04 10:00:09
【问题描述】:

我正在使用 swiftui 处理聊天视图。我确实有如下的可散列结构

struct ChatMessage : Hashable {
    var message: String
    var isMe: Bool
    var avatar: String
}

它工作正常。但是,如果我将头像数据类型更改为图像,那么我会收到错误消息,因为 "Type 'ChatMessage' does not conform to protocol 'Hashable'"

struct ChatMessage : Hashable {
    var message: String
    var isMe: Bool
    var avatar: Image
}

如何将对象(图像)包含在确认 Hashable 的结构中。

【问题讨论】:

  • 我建议添加一个唯一的id 并(仅)使用它作为哈希值。
  • 我认为您必须创建自己的类型,例如HashableImage 使用 Swift 的 Hashable 协议。这里是苹果官方文档:developer.apple.com/documentation/swift/hashable

标签: swift swiftui hashable


【解决方案1】:

SwiftUI Image 是不符合 Hashable 协议的不透明结构,并且不提供用于自定义哈希的任何属性,因此您可以在模型哈希中忽略它(不理想)或在模型中使用关于图像的一些信息参与哈希的方式(更可取)。

案例 a) - 忽略

struct ChatMessage : Hashable {

    func hash(into hasher: inout Hasher) {
        hasher.combine(message)
        hasher.combine(isMe)
    }

    var message: String
    var isMe: Bool
    var avatar: Image
}

案例 b) - 包括

struct ChatMessage : Hashable {

    var message: String
    var isMe: Bool
    var avatarName: String // avatar's name included in hash automatically

    var avatar: Image { // calculable property not used by hashing
       Image(avatarName)
    }
}

【讨论】:

    【解决方案2】:

    你可以使用这个例如:

    struct ChatMessage : Hashable {
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(UUID())
        }
    
        var message: String
        var isMe: Bool
        var avatar: Image
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-04
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多