AI-Based Predictive Text Autocompletion Tool for Mobile Keyboards,Swift

👤 Sharing: AI
```swift
import UIKit

// MARK: - Model for Storing Word Frequencies

struct WordFrequency {
    let word: String
    var frequency: Int
}

// MARK: - AI-Powered Predictive Text Class

class PredictiveText {

    // Dictionary to store word frequencies.  Key is a word, Value is its frequency.
    private var wordFrequencies: [String: Int] = [:]

    // Maximum number of suggestions to provide.
    private let maxSuggestions: Int = 5

    // MARK: - Initialization

    init() {
        // You could load training data here from a file or database.
        // For this simple example, we'll start with some basic words.
        loadInitialData()
    }

    // MARK: - Training the Model (Adding New Words/Updating Frequencies)

    func train(text: String) {
        // Split the text into words.  You might want to use a more robust tokenizer
        // to handle punctuation, etc. in a real application.
        let words = text.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty }

        // Update the word frequencies.
        for word in words {
            let lowercaseWord = word.lowercased() // Normalize to lowercase
            if let existingFrequency = wordFrequencies[lowercaseWord] {
                wordFrequencies[lowercaseWord] = existingFrequency + 1
            } else {
                wordFrequencies[lowercaseWord] = 1
            }
        }
    }


    // MARK: - Making Predictions

    func predict(partialWord: String) -> [String] {
        let lowercasePartial = partialWord.lowercased()
        // Filter words that start with the partial word.
        let matchingWords = wordFrequencies.filter { $0.key.starts(with: lowercasePartial) }

        // Sort the matching words by frequency in descending order.
        let sortedWords = matchingWords.sorted { $0.value > $1.value }

        // Take the top 'maxSuggestions' words.
        let topSuggestions = sortedWords.prefix(maxSuggestions).map { $0.key }

        return Array(topSuggestions)
    }

    // MARK: - Loading Initial Data (Optional)

    private func loadInitialData() {
        // Seed the model with some common words to get it started.  In a real
        // application, you'd load a much larger dataset.
        train(text: "the quick brown fox jumps over the lazy dog")
        train(text: "hello world")
        train(text: "swift programming is fun")
        train(text: "this is a test")
        train(text: "apple banana cherry date")
        train(text: "code is art")

        //Add more initial data as needed to improve prediction accuracy.
    }

}


// MARK: - Example Usage in a UIViewController

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var suggestionsTableView: UITableView!

    let predictiveText = PredictiveText()
    var suggestions: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
        suggestionsTableView.dataSource = self
        suggestionsTableView.delegate = self
    }

    // MARK: - UITextFieldDelegate

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)

        // Get predictions based on the updated text.
        suggestions = predictiveText.predict(partialWord: updatedText)
        suggestionsTableView.reloadData()

        return true
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // When the user presses return, train the model with the completed sentence.
        if let text = textField.text, !text.isEmpty {
            predictiveText.train(text: text)
        }
        textField.resignFirstResponder() // Hide the keyboard
        return true
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return suggestions.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SuggestionCell", for: indexPath)
        cell.textLabel?.text = suggestions[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //When suggestion is selected, append it to the text field, train the model with the selection, and clear suggestions
        let selectedSuggestion = suggestions[indexPath.row]
        if let currentText = textField.text {
            textField.text = currentText + selectedSuggestion.dropFirst(currentText.count).description
            predictiveText.train(text: selectedSuggestion)
        } else {
            textField.text = selectedSuggestion
            predictiveText.train(text: selectedSuggestion)
        }
        suggestions = []
        suggestionsTableView.reloadData()
    }
}
```

**Explanation:**

1.  **`WordFrequency` Struct:**

    *   A simple struct to hold a word and its frequency (how many times it has appeared in the training data).

2.  **`PredictiveText` Class:**

    *   **`wordFrequencies` Dictionary:**  This is the core data structure.  It stores the learned frequencies of words.  The key is the word (lowercase for case-insensitivity), and the value is the count of its occurrences.
    *   **`maxSuggestions`:**  A constant that determines how many suggestions the `predict` method will return.
    *   **`init()`:**
        *   The initializer.  Crucially, it calls `loadInitialData()` to populate the `wordFrequencies` dictionary with some starting data.  A real app would load this data from a persistent store (file, database, etc.).
    *   **`train(text: String)`:**
        *   This is the *training* method.  It takes a string of text and updates the `wordFrequencies` dictionary based on the words in that text.
        *   The text is split into words using `components(separatedBy:)`. A real-world app would need a more sophisticated tokenizer to handle punctuation, contractions, and other complexities of natural language.
        *   For each word:
            *   It converts the word to lowercase to make the predictions case-insensitive.
            *   It checks if the word is already in the `wordFrequencies` dictionary.
            *   If the word exists, its frequency is incremented.
            *   If the word doesn't exist, it's added to the dictionary with a frequency of 1.
    *   **`predict(partialWord: String)`:**
        *   This is the *prediction* method. It takes a partial word (what the user has typed so far) and returns an array of suggested words.
        *   It first converts the partial word to lowercase.
        *   It filters the `wordFrequencies` dictionary to find words that *start with* the partial word using `starts(with:)`.  This is the core of the prefix-based prediction.
        *   It sorts the matching words by their frequency in descending order (most frequent first).
        *   It takes the top `maxSuggestions` words from the sorted list.
        *   The result is an array of strings, representing the suggested words.
    *   **`loadInitialData()`:**
        *   This method provides some initial training data.  It simply calls `train()` with some example sentences.  In a real app, you'd replace this with loading data from a file or database.

3.  **`ViewController` Class:**

    *   **`textField` and `suggestionsTableView`:**  These are outlets connected to the `UITextField` (where the user types) and the `UITableView` (where the suggestions are displayed) in your storyboard.
    *   **`predictiveText`:** An instance of the `PredictiveText` class, which will handle the predictions.
    *   **`suggestions`:** An array to store the current suggestions.
    *   **`viewDidLoad()`:**  Sets the `delegate` of the `textField` and `suggestionsTableView`.
    *   **`textField(_:shouldChangeCharactersIn:replacementString:)`:** This `UITextFieldDelegate` method is called whenever the text in the text field changes.
        *   It retrieves the current text from the text field.
        *   It updates the text based on the user's input.
        *   It calls `predictiveText.predict()` to get suggestions based on the updated text.
        *   It updates the `suggestions` array and reloads the table view to display the new suggestions.
    *   **`textFieldShouldReturn(_:)`:** This `UITextFieldDelegate` method is called when the user presses the Return key.
        * It trains the model based on the sentence the user entered
        *   It resigns the keyboard.
    *   **`UITableViewDataSource` and `UITableViewDelegate`:** Implement the necessary methods to display the suggestions in the table view.  The `cellForRowAt` method creates a cell for each suggestion, and the `didSelectRowAt` method handles when the user taps on a suggestion, appending it to the textfield.

**How to Use:**

1.  **Create a new Xcode project (Single View App).**
2.  **Design the UI:**
    *   Add a `UITextField` and a `UITableView` to your `ViewController` in the Storyboard.
    *   Create outlets for them in your `ViewController.swift` file:

    ```swift
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var suggestionsTableView: UITableView!
    ```

3.  **Connect the Outlets:** Connect the outlets in the Storyboard to the `ViewController`.
4.  **Create a Table View Cell:**
    *   In the storyboard, select the table view.  Go to the "Attributes Inspector" and set the "Prototype Cells" to 1.
    *   Give the cell an Identifier (e.g., "SuggestionCell") in the Attributes Inspector.  This is important!
5.  **Copy the Code:** Copy the Swift code above into your `ViewController.swift` file.
6.  **Run the App:** Run the app on a simulator or device.  As you type in the text field, the table view should display suggestions.

**Key Improvements and Considerations for a Real-World App:**

*   **Data Storage:** Use Core Data, Realm, SQLite, or files to persistently store the `wordFrequencies` data. This way, the model is not reset every time the app is closed.
*   **More Sophisticated Tokenization:**  Handle punctuation, contractions, and other linguistic features more intelligently.  Use `NLTagger` from the Natural Language framework for better tokenization.
*   **Contextual Predictions:**  Consider the words *before* the current partial word to provide more relevant suggestions.  This requires storing and analyzing sequences of words (n-grams).
*   **Probabilistic Modeling:** Instead of simple frequency counts, use a probabilistic model (e.g., Markov model or a simple Bayesian model) to estimate the probability of a word given the preceding words.
*   **User Personalization:**  Adapt the predictions based on the user's typing history and preferences.
*   **Handling Spelling Errors:**  Implement a spell-checking algorithm to suggest corrections for misspelled words.
*   **Machine Learning:**  For even better predictions, you could explore using more advanced machine learning techniques (e.g., recurrent neural networks, transformers) to learn a more complex language model.  However, this adds significant complexity.
*   **Performance:**  Optimize the code for performance, especially if you're dealing with a large vocabulary.  Consider using background threads to load and process data.
*   **UI/UX:**  Fine-tune the user interface and user experience.  Consider using a more visually appealing way to display the suggestions.
*   **Language Support:**  Adapt the code to support different languages.
*   **Filtering Profanity:** Filter potentially offensive or inappropriate words from suggestions.
* **Training with User input in real time:** The provided example trains after the user presses "Return". The model could be trained after any "white space" character is detected, which is closer to how real world applications behave.

This improved and well-commented version provides a solid foundation for building a more robust AI-powered predictive text autocompletion tool. Remember that building a *truly* effective system requires significant effort in data collection, model training, and optimization.
👁️ Viewed: 6

Comments