Created
September 24, 2021 18:52
-
-
Save dmytro-anokhin/29875209ec841481e2a0c48d90259534 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@MainActor | |
final class AutocompleteObject: ObservableObject { | |
let delay: TimeInterval = 0.3 | |
@Published var suggestions: [String] = [] | |
init() { | |
} | |
private let citiesCache = CitiesCache(source: CitiesFile()!) | |
private var task: Task<Void, Never>? | |
func autocomplete(_ text: String) { | |
guard !text.isEmpty else { | |
suggestions = [] | |
task?.cancel() | |
return | |
} | |
task?.cancel() | |
task = Task { | |
await Task.sleep(UInt64(delay * 1_000_000_000.0)) | |
guard !Task.isCancelled else { | |
return | |
} | |
let newSuggestions = await citiesCache.lookup(prefix: text) | |
if isSuggestion(in: suggestions, equalTo: text) { | |
// Do not offer only one suggestion same as the input | |
suggestions = [] | |
} else { | |
suggestions = newSuggestions | |
} | |
} | |
} | |
private func isSuggestion(in suggestions: [String], equalTo text: String) -> Bool { | |
guard let suggestion = suggestions.first, suggestions.count == 1 else { | |
return false | |
} | |
return suggestion.lowercased() == text.lowercased() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment