错误 "Expression type '@lvalue String?' is ambiguous without more context" 是什么意思?

What does error "Expression type '@lvalue String?' is ambiguous without more context" mean?

在 TableView Controller 中,我有多个 UITextField,允许用户输入一些信息并使用 Realm 保存用户输入的数据。

我使用以下方法添加数据,但出现错误 "Expression type '@lvalue String?' is ambiguous without more context"

import UIKit
import RealmSwift

class NewIdeaCreation: UITableViewController, UITextFieldDelegate {

   let realm = try! Realm()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}    

@IBAction func createButtonPressed(_ sender: UIButton) {

    try realm.write {
        realm.add(nameTextField.text) //Error here
    }
    self.dismiss(animated: true, completion: nil)
}


@IBOutlet weak var nameTextField: UITextField!

}

我应该在这里做什么?

  • 首先添加对象模型
class Item: Object {

    @objc dynamic var itemId: String = UUID().uuidString
    @objc dynamic var body: String = ""
    @objc dynamic var isDone: Bool = false
    @objc dynamic var timestamp: Date = Date()

    override static func primaryKey() -> String? {

        return "itemId"

    }


}
  • 更新您的代码
 @IBAction func createButtonPressed(_ sender: UIButton) {

        try realm.write {
            realm.add(nameTextField.text) //Error here
        }

        self.dismiss(animated: true, completion: nil)

    }
  • 致此
 @IBAction func createButtonPressed(_ sender: UIButton) {

        let item = Item()
        item.body = nameTextField.text ?? ""
        try! self.realm.write {
        self.realm.add(item)
       }

        self.dismiss(animated: true, completion: nil)

    }

您只能将 Realm Object 保存到领域数据库中。 String 不是 Realm Object

您可以创建一个具有 String 的对象:

class StringObject: Object {
    @objc dynamic var string = ""
    // Your model probably have more properties. If so, add them here as well
    // If not, that's ok as well
}

现在您可以保存 StringObject 而不是:

do {
    try realm.write {
        let stringObject = StringObject()
        stringObject.string = nameTextField.text ?? ""
        realm.add(stringObject)
    }
} catch let error {
    print(error)
}