swift - 在 Swift 中创建数组集

标签 swift

我试图从数组 中创建一个集合 以使元素独一无二。 我认为使用 Set 初始值设定项来完成这项工作是一种优雅的方法。所以我创建了一个数组,并尝试使用该数组初始化我的新集合。 但是编译器在提示。我尝试使用 Integer 值,它就像一个魅力。但是对于我自己的类(class),这是行不通的。我还认为 Equatable Protocol 是正确的方法..但如您所见,它并没有解决我的问题。

考虑以下 Playground :

 import UIKit

internal struct Object: Equatable {
    var a: Int
}

internal func == (lhs:Object,rhs: Object) -> Bool {
    return lhs.a == rhs.a
}

let array = [Object(a:1),Object(a:1),Object(a:1),Object(a:1),Object(a:2)]

let set = Set(array) // ERROR

编译器正在提示

can not invoke initializer Set<_> with argument of type [Object]

我需要实现哪个协议(protocol)才能使事情正常进行?

最佳答案

如果您在 Xcode 中“按住命令单击”Set,它会将您带到 Set 类型的定义。然后你去:

/// A collection of unique `Element` instances with no defined ordering.
public struct Set<Element : Hashable> : Hashable, CollectionType ...

正如 Rob 所提到的,元素需要确认为 Hashable(这又需要 Equatable)。

调整代码:

import Foundation

internal struct Object: Hashable {
    var a: Int
    var hashValue: Int { return a.hash }
}

internal func == (lhs:Object,rhs: Object) -> Bool {
    return lhs.a == rhs.a
}

let array = [Object(a:1),Object(a:1),Object(a:1),Object(a:1),Object(a:2)]

let set = Set(array) // SUCCESS

关于swift - 在 Swift 中创建数组集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39230637/

相关文章:

swift - 处理两种文档类型

ios - UISwipeGestureRecognizer for swift on xcode

ios - 在 safari/app store 中快速打开链接

swift 3 : Segue and pass in data from one class to another

swift - 关闭 - deinit self 对象的时间

function - Swift、数学函数和协议(protocol)

swift - 向 SDCAlertView 添加图标

swift - 我们如何使键盘快速出现在textView下方?

ios - 向 UITextView 添加阴影会使文本扩展到 UITextViewFrame 之外

swift - 如何将不同 dic 的值分配给 UIlabel