【问题标题】:Why Swift Set fucntion Why firstIndex(of: ) Apply?为什么 Swift Set 函数为什么要应用 firstIndex(of:)?
【发布时间】:2022-12-07 21:26:55
【问题描述】:

我了解 Set Collection 是键值对并且键不重复。

在下面的示例中,我认为水果是关键。

但是 .firstIndex(of: ) 为什么存在?

那么第二个索引可以存在吗?

我对集合有误解吗?

var favoriteFruits: Set = ["Banana", "Apple", "Orange", "Orange"]

favoriteFruits.insert("WaterMelon")
print(favoriteFruits)
favoriteFruits.remove("Banana")
print(favoriteFruits)

if favoriteFruits.contains("Tomato") {
    print("Tomato is my favorite Fruits")
} else {
    print("Tomato is not my favorite Fruits")
}

print(favoriteFruits.firstIndex(of: "Orange"))

如果您发表评论,将会有很大帮助。

【问题讨论】:

  • 我了解 Set Collection 是键值对.有点,但是钥匙(又名哈希)不会暴露给用户。从用户的角度来看,Set 和 Array 一样是基于索引的,但项目是唯一且无序的。

标签: swift set


【解决方案1】:

如果你检查firstIndexOf method's explanition你会看到一个定义:

Available when Element conforms to Equatable.

集合符合Equatable。您也可以在检查两个集合是否相等时进行测试。下面的代码没有给出任何错误。

if set1 == set2{
  //....
}

你问 .firstIndex(of: ) 为什么存在?

所以Set的集合类型使用firstIndexOf方法没有障碍

如果你问why set is equatable.Set 使用哈希表来检查里面的元素。所以Set must be hashable。符合Hashable的对象也必须是Equatable

【讨论】:

    【解决方案2】:

    这是 Set<String> 符合 Collection<String> 的结果。 Collection协议需要this method

    func firstIndex(of element: Self.Element) -> Self.Index?
    

    Collection 协议也需要关联类型 ElementIndex。即使Set 不是索引-基于, Set 确实声明了一个名为 Index 的嵌套结构。查看它的实现here

    的确,特定元素不可能有“第二个”索引,因为集合中的元素是唯一的。 firstIndex(of:)lastIndex(of:) 对于集合的任何元素都会返回相同的东西。

    但是,Collection 协议并不关心。毕竟,可以采用任何 Collection 的函数并不知道它们正在使用哪种类型的集合,例如

    func someGenericFunction<C: Collection>(collection: C) {
        // ...
    }
    

    因此他们需要指定他们是否需要特定元素的第一个、最后一个或第 n 个索引,以便他们的代码适用于所有类型的集合。如果Set没有这些方法,那么Set就不是Collection,不能传递给这些函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多