0

I can't pass in the data from ViewController to NewVC --another UIViewController . I have been stuck here for hours with no result so this is my last resort for solving this.

For underlaying idea :

My Code For ViewController

class ViewController: UIViewController{
    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var lastName: UITextField!
   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    switch segue.identifier {
        
    case "seg_One"? :
        
        if let source = segue.source as? ViewController
            ,let destination = segue.destination as? NewVC {
            
                destination.name.text = source.name.text  //Error    
                destination.lastName.text = source.lastName.text //Error

            }

        default: break
        
        }

    }

// Bunch of other code such as ViewDidLoad()
}

NewVC code:

class NewVC: UIViewController {

  @IBOutlet weak var name: UILabel!
  @IBOutlet weak var lastName: UILabel!

  override func viewDidLoad() {
     super.viewDidLoad()

   }    

}

Error is: fatal error: unexpectedly found nil while unwrapping an Optional value

Community
  • 1
  • 1
Biken
  • 61
  • 2
  • 11
  • 4
    It's because when `prepareForSegue()` is called the `IBOulet` are not loaded yet and are nil. You have to create public String properties. – Larme Aug 01 '17 at 13:43
  • https://stackoverflow.com/questions/38357065/unexpectedly-found-nil-iboutlet-in-prepareforsegue https://stackoverflow.com/questions/29239648/prepareforsegue-not-setting-uilabel https://stackoverflow.com/questions/9576177/how-can-i-set-the-value-of-a-uilabel-following-a-segue https://stackoverflow.com/questions/25422536/swift-prepareforsegue-fatal-error-unexpectedly-found-nil-while-unwrapping-an – Larme Aug 01 '17 at 13:44
  • Thanks Larme. :) – Biken Aug 01 '17 at 13:51
  • You can mark your question as a duplicate of any of theses other questions ;) – Larme Aug 01 '17 at 13:51

1 Answers1

0

Change as below

class NewVC: UIViewController {

   var strName: String?
   var strLastName: String?

  @IBOutlet weak var name: UILabel!
  @IBOutlet weak var lastName: UILabel!



  override func viewDidLoad() {
     super.viewDidLoad()
     self.name = self.strName
     self.lastName = self.strLastName

   }    

}

Assign while segue as below

destination.strName = source.name.text 
 destination.strLastName= source.lastName.text 
KKRocks
  • 8,222
  • 1
  • 18
  • 84