Fuse 是一个超轻量级的库,它提供了一种简单的方法来进行模糊搜索。
let fuse = Fuse()
let result = fuse.search("od mn war", in: "Old Man's War")
print(result?.score) // 0.44444444444444442
print(result?.ranges) // [CountableClosedRange(0...0), CountableClosedRange(2...6), CountableClosedRange(9...12)]
在一个字符串数组中搜索文本模式。
let books = ["The Silmarillion", "The Lock Artist", "The Lost Symbol"]
let fuse = Fuse()
// Improve performance by creating the pattern once
let pattern = fuse.createPattern(from: "Te silm")
// Search for the pattern in every book
books.forEach {
let result = fuse.search(pattern, in: $0)
print(result?.score)
print(result?.ranges)
}
class Book: Fuseable {
dynamic var name: String
dynamic var author: String
var properties: [FuseProperty] {
return [
FuseProperty(name: "title", weight: 0.3),
FuseProperty(name: "author", weight: 0.7),
]
}
}
let books: [Book] = [
Book(author: "John X", title: "Old Man's War fiction"),
Book(author: "P.D. Mans", title: "Right Ho Jeeves")
]
let fuse = Fuse()
let results = fuse.search("man", in: books)
results.forEach { item in
print("index: " + item.index)
print("score: " + item.score)
print("results: " + item.results)
print("---------------")
}
// Output:
//
// index: 1
// score: 0.015
// results: [(key: "author", score: 0.015000000000000003, ranges: [CountableClosedRange(5...7)])]
// ---------------
// index: 0
// score: 0.028
// results: [(key: "title", score: 0.027999999999999997, ranges: [CountableClosedRange(4...6)])]
let fuse = Fuse()
fuse.search("Man", in: books, completion: { results in
print(results)
})
Fuse
接受以下选项
location
: 期望在文本中找到模式的大概位置。默认为 0
distance
: 确定匹配必须与模糊 location
(如上所述) 多接近。一个精确的字母匹配,距离模糊位置 distance
个字符,将被视为完全不匹配。 distance
为 0
要求匹配位于指定的精确 location
,distance
为 1000
要求在模糊位置 800
个字符内存在一个完美的匹配,才能使用 0.8 的阈值找到。默认为 100
threshold
: 匹配算法在哪个点放弃。 阈值为 0.0
需要一个完美的匹配(字母和位置都要匹配),阈值为 1.0
会匹配任何东西。 默认为 0.6
maxPatternLength
: 最大有效模式长度。 模式越长,搜索操作的强度就越大。 如果模式超过 maxPatternLength
,则 search
操作将返回 nil
。 为什么这很重要? 阅读此内容。 默认为 32
isCaseSensitive
: 指示比较是否应区分大小写。 默认为 false
要运行示例项目,请克隆该仓库,然后首先从 Example 目录运行 pod install
。
Fuse 可通过 CocoaPods 获得。 要安装它,只需将以下行添加到您的 Podfile 中
pod "Fuse"
Fuse 在 MIT 许可证下可用。 有关更多信息,请参阅 LICENSE 文件。