Guest User

Untitled

a guest
Jul 17th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import Foundation
  2. import os.log
  3.  
  4. final class Searcher {
  5.  
  6. struct Result: Equatable {
  7. let count: Int
  8. let hasMore: Bool
  9. }
  10.  
  11. let indexer: Indexer
  12.  
  13. init(index: Indexer) {
  14. self.indexer = index
  15. }
  16.  
  17. func search(query: String) -> Result {
  18. let flushed = indexer.flush()
  19. print("Flushed = \(flushed ? "yes": "no")")
  20.  
  21. let options = SKSearchOptions(kSKSearchOptionDefault)
  22. let skSearch = SKSearchCreate(indexer.index, query as NSString, options).takeRetainedValue()
  23.  
  24. var documentIDs = [SKDocumentID]()
  25. var scores = [Float]()
  26. var foundCount = 0
  27.  
  28. let hasMore = SKSearchFindMatches(skSearch, 100, &documentIDs, &scores, 0, &foundCount)
  29.  
  30. return Result(count: foundCount, hasMore: hasMore)
  31. }
  32. }
  33.  
  34. final class Indexer {
  35. enum IndexerError: Error {
  36. case unableToCreate
  37. }
  38.  
  39. let index: SKIndex
  40.  
  41. init(url: URL, name: String) throws {
  42. guard let index = SKIndexCreateWithURL(url as NSURL, name as NSString, SKIndexType(kSKIndexInverted.rawValue), nil)?.takeRetainedValue() else {
  43. throw IndexerError.unableToCreate
  44. }
  45.  
  46. self.index = index
  47. }
  48.  
  49. func flush() -> Bool {
  50. return SKIndexFlush(index)
  51. }
  52.  
  53. func index(_ source: Searchable) {
  54. let objectURL = source.URIRepresentation as NSURL
  55. let document = SKDocumentCreateWithURL(objectURL).takeRetainedValue()
  56. let indexed = SKIndexAddDocumentWithText(index, document, source.summary as NSString, true)
  57. os_log("Indexed to disk: %@", indexed ? "true" : "false")
  58.  
  59. let flushed = self.flush()
  60. os_log("Flushed index to disk: %@", flushed ? "true" : "false")
  61. }
  62.  
  63. func createSearch() -> Searcher {
  64. return Searcher(index: self)
  65. }
  66.  
  67. func search(query: String) -> Searcher.Result {
  68. return createSearch().search(query: query)
  69. }
  70.  
  71. }
Add Comment
Please, Sign In to add comment