【问题标题】:Swift 5.+ - Making a class hashable?Swift 5.+ - 使类可散列?
【发布时间】:2020-05-07 02:38:44
【问题描述】:

我对 swift 很陌生,所以请原谅任何明显的误解。我试图研究但没有好的答案。

我有一个具有以下迭代的 NavigationView

ForEach(listOfStuff, id: \.self)

listOfStuff 被定义为符合 Hashable 的结构,一切正常。

我想将结构更改为一个类,但不知道如何使该类成为 Hashable 以便 \.self 工作(它一直抱怨该类必须是 Hashable)

示例已经过时或一直在谈论结构。我什至不知道我是否可以在 ForEach 中使用一个类?我该怎么办?

谢谢

【问题讨论】:

  • 你当然可以让一个类可散列。但问题是它不会像结构那样自动进行哈希处理(当您声明符合 Hashable 时)。如果你使用一个类,你必须你自己实现哈希。

标签: swift swiftui swift5


【解决方案1】:

这是在所描述的用例中使用基于类的模型的示例。使用 Xcode 11.4 测试

class Stuff: Hashable, Equatable {
    static func == (lhs: Stuff, rhs: Stuff) -> Bool {
        lhs.title == rhs.title
    }

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

    var title: String = ""
}

struct StaffView: View {
    let listOfStaff: [Stuff]

    var body: some View {
        ScrollView {
            ForEach(listOfStaff, id: \.self) { stuff in
                Text(stuff.title)
            }
        }
    }
}

【讨论】:

  • 谢谢,这为我解决了。我在我的代码中编写哈希函数,但从未意识到我还必须编写静态 func = ... 这让我发疯了。
【解决方案2】:

参见Adopting Common ProtocolsHashable documentation,两者都概述了制作Hashable 的过程,如outlined by Asperi

但您不必制作全部内容Hashable。您可以提供一些可以识别它的属性,例如

class Item {
    let id: UUID
    let string: String

    init(string: String) {
        self.id = UUID()
        self.string = string
    }
}

struct ContentView: View {
    let items: [Item]
    var body: some View {
        ScrollView {
            ForEach(items, id: \.id) { item in
                Text(item.string)
            }
        }
    }
}

或者,更好的是,将其设为Identifiable,例如

class Item: Identifiable {
    let id: UUID
    let string: String

    init(string: String) {
        self.id = UUID()
        self.string = string
    }
}

struct ContentView: View {
    let items: [Item]
    var body: some View {
        ScrollView {
            ForEach(items) { item in
                Text(item.string)
            }
        }
    }
}

如果您愿意,可以将其设为 Hashable,但对于 ForEach 而言,Identifiable 更简单且足够。

【讨论】:

  • 这也很有帮助,谢谢。看例子,我开始理解这个概念。
猜你喜欢
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 2012-11-10
  • 2015-07-05
  • 2017-07-11
  • 1970-01-01
相关资源
最近更新 更多