Jack
Jack

Reputation: 1086

instance member cannot be used on type view controller

I have seen many posts on stack overflow but none of them helped me. I am taking a course on udemy and my teacher had no problem doing

var age = Int(catAge.text);

but for some reason, I get an error saying

Instance member 'catAge' cannot be used on type view controller

Here is my full view controller:

import UIKit
class ViewController: UIViewController {
@IBOutlet var catAge: UITextField!
@IBOutlet var result: UILabel!
var age = Int(catAge.text)
@IBAction func submit(sender: AnyObject) {
    result.text = age * 7
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
override func didRecieveMemoryWarning() {
super.didRecieveMemoryWarning()
// Dispose of any resources that can be recreated.
}

I also get an error saying that I can't multiply Int? and Int.

Upvotes: 0

Views: 4292

Answers (1)

luk2302
luk2302

Reputation: 57184

The line var age = Int(catAge.text) is invalid in the context where you write it - as instance variable. You can write that line in the scope of a method, but it does not make any sense at the given point - what is supposed to happen? First of catAge is nil, secondly if it wasn't the text would certainly be empty because no user has had any chance to input anything yet.

And age is of type Int? since it is not certain you can convert the text to an int. To multiply the age you have to unwrap it, or better check wether or not it even can be converted to int:

@IBAction func submit(sender: AnyObject) {
    if let age = Int(catAge.text) {
        result.text = age * 7
    } else {
        result.text = "please input an integer"
    }
}

Upvotes: 2

Related Questions