I'm building an emoji search bar where you can type and get the relevant emojis to show up - similar to what Apple does on its keyboard. For that, I've precomputed static word embeddings for all the emojis and saved it in a .mlmodel
file. My task is to compute the word embedding for the search query and look it up in the mlmodel
.
Issue: Whenever I try to call NLEmbedding.vector(for: String)
method, it returns a nil
value. This happens only when the parameter is linked to a SwiftUI @State var
. If it is a String literal, than it works perfectly fine.
Here's a miniumum reproducible example for the same.
import SwiftUI
import NaturalLanguage
struct ContentView: View {
@State private var searchText = ""
var body: some View {
VStack {
TextField("Search emojis", text: $searchText)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(12)
.onChange(of: searchText, perform: searchEmojis(forQuery:))
}
.padding()
}
private func searchEmojis(forQuery text: String) {
guard let embedding = NLEmbedding.wordEmbedding(for: .english) else { return }
let queryVector = embedding.vector(for: text) // Works fine for a string literal
print("Query vector: \(queryVector)") // Returns a nil vector
}
}
What I'm looking for: A way to retrieve user input and compute the word embedding dynamically.