swift - 如何在 swift 中使用自定义类型的字典中使用/引用键?

标签 swift

我有一个字典 (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/

相关文章:

swift - 如何设置自动布局以使图像占据全屏?

ios - Xcode 13.2 中为 iOS 13 宣布的 Swift Concurrency - 他们是如何实现这一目标的?

ios - TextView和TextField的单个扩展以添加工具栏

c++ - 在 SWIFT 中使用 C++ FFT 代码

swift - 在标准 View Controller 中更改 TableView 单元格

swift - 是否可以从 mapKit 获取纬度和经度并在谷歌地图中使用它?

iOS8 swift : deleteRowsAtIndexPaths crashes

ios - 我如何在 iOS Swift 的单个项目中使用两个 GMSMapViews

ios - Swift - 将操作事件更改为 UITextField

ios - 如何抑制 UINavigationController 栏中的默认 'edit' 按钮?