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

此生再无相见时 提交于 2021-01-29 10:51:15

问题


In a TableView Controller, I have multiple UITextFields that allow users to input some information and use Realm to save data from users' input.

I use the following ways to add the data but I got the error saying "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!

}

What should I do here?


回答1:


You can only save Realm Objects into a realm database. String is not an Realm Object.

You can create an object that has a String though:

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
}

Now you can save a StringObject instead:

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



回答2:


  • First Add Object Model
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"

    }


}
  • Update Your Code
 @IBAction func createButtonPressed(_ sender: UIButton) {

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

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

    }
  • To This
 @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)

    }



来源:https://stackoverflow.com/questions/56752579/what-does-error-expression-type-lvalue-string-is-ambiguous-without-more-con

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!