0

I created a var in my ViewController:

class ViewController: UIViewController {
var options: Options?

}

In viewWillAppear I set the options

/ grab the options
    let optionsFetch: NSFetchRequest<Options> = Options.fetchRequest()

    do{
        let results = try coreDataStack.managedContext.fetch(optionsFetch)
        if(results.count > 0){
            options = results.first
        }
    }catch let error as NSError{
        print("\(error) is the error")
    }

I also have an extension of this:

extension UIViewController {
func myMethod() {
let color = options.color
}

I can't seem to access the options var from within the extension. I found this post, and thought I had followed what they were saying, but still no luck. enter link description here

icekomo
  • 9,328
  • 7
  • 31
  • 59
  • You have extended the wrong class; `extension ViewController` is what you probably want instead. – Alladinian Sep 12 '18 at 13:47
  • You have extended the general UIViewController class which has no member variable 'options'. You have to extend your custom ViewController instead – Shadrach Mensah Sep 12 '18 at 14:06

1 Answers1

5

You got your extension wrong.

extension ViewController {
    func myMethod() {
        let color = options.color
    }
}

You seem to have extended the default UIViewController class. You should be extending your ViewController class which is a subclass of UIViewController that you created, where your variable options is available.

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
  • I think I extended like that so that other UIViewControllers could use that method. – icekomo Sep 12 '18 at 13:53
  • @icekomo. I'm afraid you cannot do that. However you can subclass UIViewController and add the options variable and add myMethod and use that class wherever necessary which is what you have in ViewController currently. So you could just create ViewController objects instead of UIViewController objects. Or create another class which has this variable and the method and make ViewController a subclass of that. – Rakesha Shastri Sep 12 '18 at 14:00