I want to extend Array to translate arrays into sets, where possible. The following extension does that but in the debugger console, the elements of the set are explicitly labeled AnyHashable. Why is this so? But more importantly, is there a way to determine the concrete type of the element (i.e. String) in the extension so that it returns a type-matching set?

extension Array where Element: Hashable {
    var asSet: Set<AnyHashable> {
        return Set(self)
    }
}

let someArray: [String] = ["kiwi", "mango", "mango"]

print(someArray.asSet) // actual output:  [AnyHashable("kiwi"), AnyHashable("mango")]
                       // desired output: ["kiwi", "mango"]

推荐答案

You can just avoid AnyHashable, and return a set of the generic type:

var asSet: Set<Element> {
    return Set(self)
}

In your example, that will return a Set<String>.

Swift相关问答推荐

自定义完整屏幕封面动画

如何使用快速宏用来自函数的关联值来初始化枚举?

如何禁用MacOS上SwiftUI中按钮周围的聚焦环(或高亮显示)?

通过SwiftUI中的列表 Select 从字典中检索值

SWIFT闭包使用的是陈旧的值,即使它是S@转义

Swift UI中视图上的值未更新

字符串和整数格式的for循环,帮忙!

从 Obj-C 函数返回 swift 类的不兼容指针类型

带有可选字符串作为键路径的 SwiftUI iOS16 表

ForEach within List:模式的好处?

Pod lib lint 命令找不到 watchos 模拟器

SwiftUI Grid 中的数组旋转

Xcode:方法参数的代码完成

如何处理永远不会失败的 String.Encoding 初始化程序?

SwiftUI 文本被意外截断

Swift 中的 PageViewController 当前页面索引

使用 DispatchTime.now() + float 延迟?

在 Swift 中为 UIPickerView 设置默认值?

如何在 SwiftUI 中的一个视图上显示两个alert ?

判断用户是否登录到 iCloud?Swift /iOS