Search code examples
iosswiftswift4inout

store reference in variable SWIFT 4


I send a parameter from my viewController to customCell. My custom cell has a textField. In my viewController I have a string variable for storing the value in textField, because this value I will send to a rest services.

MyCustomCell

customCell: TableViewCell: {
 var data: String?
 @IBOutlet weak var textField: UITextField!

 override func awakeFromNib() {
  super.awakeFromNib()
  textField.delegate = self
 }

 func setData(data: inout String) {
  self.data = data
 }
}

extension customCell: UITextFieldDelegate {
 func textFieldDidEndEditing(_ textField: UITextField) {
  data = textField.text ?? ""
 }
}

MyViewController

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCell
  cell.setData(data: &data.email)
  return cell
}

When I sent the reference to the customCell, I lost the reference in the textFieldDidEndEditing method.


Solution

  • Don't do that.

    Create a data model using a class. A class is reference type

    class Model {
    
        var name : String   
        var email : String
    
        init(name: String, email: String) {
            self.name = name
            self.email = email
        }
    }
    

    Declare the data source array

    var models = [Model]()
    

    In the cell declare a property of the model (by the way class names start with a capital letter)

    class CustomCell: TableViewCell {
    
        @IBOutlet weak var textField: UITextField!
    
        var model: Model! {
           didSet {
              textField.text = model.email
           }
        }
    
        override func awakeFromNib() {
           super.awakeFromNib()
           textField.delegate = self
        }
    }
    
    
    extension CustomCell: UITextFieldDelegate {
        func textFieldDidEndEditing(_ textField: UITextField) {
            model.email = textField.text ?? ""
        }
    }
    

    In cellForRow pass the model to the cell

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
         cell.model = models[indexPath.row]
         return cell
    }
    

    Due to the reference semantics the value in the model is preserved.