我有一个字典 (myDictionary),其中键是自定义类型 (MyClass),其中包括 2 个属性、名称和其他属性。我正在尝试设置一个选择器数组,并意识到它可能会更复杂,因为我不能只引用 myDictionary.keys 因为键是我的自定义类。我希望用 MyClass 的“name”属性填充选择器数组。
我了解到我的类必须符合“Hashable”协议(protocol),这可能与它有关,但我有点菜鸟,对这个“hashable”协议(protocol)不太了解。这是我所拥有的
class MyClass: Codable, Hashable {
var name: String
var other: MyEnumeration
init(name: String, other: MyEnumeration) {
self.name = name
self.other = other
}//end init
//to conform to Hashable - I have NO IDEA what i'm doing here
static func == (lhs: MyClass, rhs: MyClass) -> Bool {
return lhs.name == rhs.name && lhs.other == rhs.other
}
//again i have no idea what i'm doing
func hash(into hasher: input Hasher) {
}
}//end MyClass
var myDictionary = [MyClass:String]()
//as you can see, the keys are the class I created
var pickerArray: [String] = myDictionary.keys.name.sorted() //this is wrong
//the pickerArray is what I want to do - access the "name" property of
//myclass and have it as my picker array options
最佳答案
由于您想要字典中所有键的名称数组,因此您可以这样做:
var pickerArray = myDictionary.keys.map { $0.name }.sorted()
myDictionary.keys
为您提供键中的所有 MyClass
实例。 .map { $0.name }
将 MyClass
实例数组转换为相应的名称数组。
你的hash
方法应该是:
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(other)
}
如果您查看 Hashable
的文档,您可以看到一个清晰的示例。
关于swift - 如何在 swift 中使用自定义类型的字典中使用/引用键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56084375/