Search code examples
iosxcodeswiftvariablesiboutlet

Passing an IBOutlet variable to another class


I'm trying to take an IBOutlet of type UITextField, and use that variable in a function with let constants from another class... How would I go about dong this?

Example:

  • Class A

    Import UIKit
    
    class ViewController: UIViewController {
        @IBOutlet weak var userInputTextField: UITextField!
        @IBOutlet weak var labelToBeUpdated: UILabel!
    }
    
  • Class B

    Import Foundation
    
    class Data {
        let x = 10
        let y = 100
    }
    

I would like to take the userInputTextField in Class A and multiply it by x in Class B, then divide it by y in Class B... (userInput * x) / y

Thanks


Solution

  • Actually you can't multiply IBOutlets like text fields ;-)

    • Create an instance of class Data
    • Check if the text value of the text field is convertible to Int and do the math by accessing Data's properties.

    let data = Data()
    
    if let userInput = Int(userInputTextField.text) {
      let result = (userInput * data.x) / data.y
    }