danaq
danaq

Reputation: 117

Is there a way to force the text in a TextField in Swift to be non-optional?

I am making an app that takes inputs from textFields in an alertController, then stored into CoreData and eventually be displayed in a tableView.

The plan for now is to create a string to create a CSV by combining the textField.text together, something like

let string CSV = textField.text + " ," + textField2.text + " ," + ...

However, when I tried to do this, they say that I cannot force unwrap an optional value.

I tried to put a "!" in textField.text, etc but they are all still seen as optional values. The textFields, when employed in the app must always be filled, but I could not find a way to provide an error that forces the user of the app to fill in a value.

Here is my ViewController:

import UIKit
import CoreData

class ViewController: UITableViewController {

    var alarmItems: [NSManagedObject] = []
    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        navigationController?.navigationBar.barTintColor = UIColor(red: 21/255, green: 101/255, blue: 192/255, alpha: 1)
        navigationController?.navigationBar.tintColor = .white
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Alarm", style: .plain, target: self, action: #selector(addAlarmItem))
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "AlarmItems")
        do {
            alarmItems = try managedContext.fetch(fetchRequest)
        } catch let err as NSError {
            print("Failed to fetch items", err)
        }
    }

    //now to figure out how to add multiple text fields

    @objc func addAlarmItem(_ sender: AnyObject) {
        print("this works")
        let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
            guard let textField = alertController.textFields!.first, let itemToAdd = textField.text else { return }

            //guard let textField2 = alertController.textFields?.first, let itemToAdd2 = textField2.text else { return } //tried this to get the input of a second textField

            /*

            one thing I tried:
            let textField1 = alertController.textFields[0]
            let textField1String = textField1.text!

            let textField2 = alertController.textFields![1]
            let textField2String = textField2.text
            let itemToAdd = textField1String + textField2String
            */



            //var textField1String = textField1.text
            //let textField2 = alertController.textFields![1]
            //var textField2String = textField2.text


            self.save(itemToAdd)
            //self.save(itemToAdd2)
            self.tableView.reloadData()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
        //alertController.addTextField(configurationHandler: nil)
        alertController.addTextField { (textField) in
            textField.placeholder = "First"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Second"
        }

        //let combinedString = UITextField[0] + " ," + UITextField[1]
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }

    func save(_ itemName: String) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "AlarmItems", in: managedContext)!
        let item = NSManagedObject(entity: entity, insertInto: managedContext)
        item.setValue(itemName, forKey: "alarmAttributes")

        do {
            try managedContext.save()
            alarmItems.append(item)

        } catch let err as NSError {
            print("Failed to save an item", err)
        }
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return alarmItems.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let alarmItem = alarmItems[indexPath.row]
        cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
        return cell
    }
}

Upvotes: 1

Views: 385

Answers (3)

Asmin Ghale
Asmin Ghale

Reputation: 195

You can use String extension to unwrap text this way:

extension Optional where Wrapped == String{
func safe() -> String{
    if self == nil{
        return ""
    }else{
        return self.unsafelyUnwrapped
    }
}

Hope this helps.

Upvotes: 0

Dhruv Jindal
Dhruv Jindal

Reputation: 21

One of the ways you can do the error validation is that when save is pressed, do empty checks on the textfields values in a separate function and show an error alert box.

I don't think you can show some kind of error inside your initial textfield alert controller. You have to validated the text separately and then show a separate alert error alert box.

Upvotes: 0

ekscrypto
ekscrypto

Reputation: 3816

You can use compactMap to easily convert an array of optionals into an array of non-optionals.

let myStrings: [String] = alert.textfields!.compactMap { $0.text }
let myText = myStrings.joined(separator: ", ")

To learn more about compactMap, head over to https://developer.apple.com/documentation/swift/sequence/2950916-compactmap

Upvotes: 3

Related Questions