如何使用Set.intersection获取两个序列的元素列表

时间:2018-10-24 05:33:21

标签: swift

我正在学习Swift编程语言(Swift 4.2)

https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html

是否可以使用Set.intersection()编写泛型函数以返回任何两个序列的公共元素?我已经编写了以下方法(我是一名C#开发人员,正在学习,所以请原谅Swift的不良编码做法),但是有可能在不知道元素类型的情况下做到这一点吗?

func getCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Array<Any>
where T.Element: Equatable, T.Element == U.Element
{
if let lhsSet = lhs as? Set<String> {
    if let rhsSet = rhs as? Set<String> {
        return Array(lhsSet.intersection(rhsSet))
    }
} else if let lhsSet = lhs as? Set<Double> {
    if let rhsSet = rhs as? Set<Double> {
        return Array(lhsSet.intersection(rhsSet))
    }
} else if let lhsArray = lhs as? Array<String> {
    if let rhsArray = rhs as? Array<String> {
        let lhsSet = Set<String>(lhsArray)
        let rhsSet = Set<String>(rhsArray)
        return Array(lhsSet.intersection(rhsSet))
    }
}
return [T.Element]()

}

getCommonElements(["FirstName", "MiddleName", "LastName"], ["FirstName", "LastName"])
let elementsSet1 = Set<Double>([1.2, 2.4, 3.6])
let elementsSet2 = Set<Double>([1.2, 3.6])
getCommonElements(elementsSet1, elementsSet2)

1 个答案:

答案 0 :(得分:1)

是的,无论如何,您甚至都可以从输入中初始化一个Set。不管是Set还是Array,因为您的输入是Sequence,并且Set可以从Sequence初始化。 where T.Element: Hashable, T.Element == U.Element已经保证元素类型相同,并且可以做成Set

func getCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> [T.Element] 
    where T.Element: Hashable, T.Element == U.Element
{
   return Array(Set<T.Element>(lhs).intersection(Set<U.Element>(rhs)))
}

print(getCommonElements(["FirstName", "MiddleName", "LastName"], ["FirstName", "LastName"]))
let elementsSet1 = Set<Double>([1.2, 2.4, 3.6])
let elementsSet2 = Set<Double>([1.2, 3.6])
print(getCommonElements(elementsSet1, elementsSet2))

输出:

["FirstName", "LastName"]
[1.2, 3.6]