Optional(“”)被保存在数据库中

时间:2018-10-16 22:14:49

标签: swift

在Swift 4.2中,我有以下方法

cell.onPartNumberTapped = { [weak self] in
            let alert = UIAlertController(title: "Enter New Part Number", message: "", preferredStyle: .alert)

        alert.addTextField { (textField) in
            textField.placeholder = "Add/Edit Part Number"
            textField.text = ""
        }

        let action = UIAlertAction(title: "Submit", style: .default) { (action) in
            let textField = alert.textFields![0]

            let parameters = [
                "id": component.id,
                "part_number": textField.text as Any
                ] as [String : Any];

            Alamofire.request(global.API_URL + "components/edit_pn", method: .post, parameters: parameters as Parameters ).responseJSON { [weak self]
                response in

                if response.result.isSuccess {
                    //
                } else {
                    self?.showMessage(messageToDisplay: "Unable to connect to service.")
                } // end if
            }
        }

        alert.addAction(action)

        self?.present(alert, animated: true, completion: nil)
    }

AJAX调用后要保存的值为

Optional("S65-5366-2L-1X")

必须在后端使用正则表达式将其删除是正常的,还是我错过了方法中的某些内容?

1 个答案:

答案 0 :(得分:0)

使用parameters as Parameters转换字典会将textField.text的可选值转换为字符串Optional("whatever was in the text field")。为了避免这种情况,请将可选值转换为非可选值,如下所示:

let parameters = [
    "id": component.id,
    "part_number": textField.text ?? "" // if nil use the empty string, otherwise unwrap
] as [String : Any];

请注意,您的客户端可能应该通知用户有关空文本字段的信息,而不是使用默认值。