Search code examples
swiftxcodeviewcontroller

@IBOutlet property cannot have non-object type


I am trying to pass a struct between view controllers, but I get the compiler error "@IBOutlet property cannot have non-object type". I have tried to add @objc but still get the error. How can I pass this data between view controllers? Why do I get this error and how do I correct it? Thanks.

import UIKit
struct DocObject: Codable {
    let filename: String
    let doclink: Int
}

class ViewController: UIViewController {   
    @IBOutlet weak var textField: UITextField!   
    //  var nameText = ""
    var obj = DocObject(filename: "filename", doclink: 123)    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBAction func done(_ sender: Any) {
        print ("In VC1 nameText  ", obj)
        performSegue(withIdentifier: "name", sender: self)   
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! VCTwo2
        vc.finalObj = obj   
    }    
}





import UIKit
class VCTwo2: UIViewController {
    @IBOutlet var finalObj: DocObject!

    //  var finalName = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print ("In VC2  ", finalObj!)        
    }

}

Solution

  • You only define a property with @IBoutlet if the property is loaded from a xib or storyboard. Since you are passing the data structure from another view controller just define finalObj as a regular var.

    class VCTwo2: UIViewController {
        var finalObj: DocObject!
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }