Swift搜索值为最接近的相似值,无序列

时间:2017-04-17 10:44:32

标签: ios arrays swift

大家好我想问你如何在项目中搜索关于序列的最近可能的相似值。当我搜索[“餐厅”,“公牛”]时,如下所示,它应该返回我str2是可能的最近值。因为此函数只能用于订单序列,所以不能用于非序列。我真的希望你们能帮帮我....

 func search(`for` searchItems: Set<String>, `in` searchArea: [Set<String>]) -> Set<String>? {
            return searchArea.max(by: { (a, b) -> Bool in
                return searchItems.intersection(a).count < searchItems.intersection(b).count || searchItems.intersection(a).count > searchItems.intersection(b).count
            })
        }        


            let str2: Set<String> = ["Bull","Restaurant","Corner"]
            let str3: Set<String> = ["Corner","Restaurant","Mole"]

            let area = [str3, str2] as [Any]

            print("search result",self.search(for: ["Restaurant","Bull"], in: area as! [Set<String>]))

2 个答案:

答案 0 :(得分:1)

可能是因为您的str2str3根本不是Set,它的数组是因为您正在使用数组声明,因此将其更改为此然后它可以正常工作使用["Bull", "Restaurant"]

let str2 = Set(["Bull","Restaurant","Corner"])
let str3 = Set(["Corner","Restaurant","Mole"])

此外,Set是非有序序列,Array是有序序列

答案 1 :(得分:0)

只需设置一个查询数组并使用其isSubset(of:)方法检查它是否是您数据的一个子集。

let set1 = Set([1,2,3])
let set2 = Set([2,3,4])

let query = [1,2]
let querySet = Set(query)

querySet.isSubset(of: set1) // true
querySet.isSubset(of: set2) // false

let query2 = [2,1]
let querySet2 = Set(query)

querySet2.isSubset(of: set1) // true
querySet2.isSubset(of: set2) // false