Search code examples
iosswiftxcodexcode11

Error to show the calculation error on iOS app


I'm creating iOS app that respond the inputted variables.

However, there is one error message to print the result and I have no idea to fix the error.

First Error Message

        let result = x + y
        label.text = "result is \(result) "

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

What I tried to do

After getting the first comment, I have double checked ResultViewController.swift and the transition page was changed.

What I need is to show result is 2 instead res... How can I fix it?

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // aquire ResultViewController from segue
        let resultViewController:ResultViewController = segue.destination as! ResultViewController
        // set numbers
        resultViewController.x = 1
        resultViewController.y = 1
    }

    @IBAction func unwind(_ segue: UIStoryboardSegue) {
        // called after returning back from segue 
    }
}

ResultViewController.swift

import UIKit

class ResultViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    var x:Int = 0
    var y:Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let result = x + y
        label.text = "result is \(result) "
    }
}


Solution

  • Add constraints on your label either from storyboard or programatically

     override func viewDidLoad() {
             super.viewDidLoad()
    
                label.translatesAutoresizingMaskIntoConstraints = false
                label.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
                label.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
                label.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
                label.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    
                let result = x + y
                label.text = "result is \(result) "
            }
    

    or whatever constraint you want to add on your label