0

I have a very simple NSViewController , which hits an API using a WeatherFetcher class. It passes a completion handler as a parameter, so that the HTTP API can call it once it finishes.

In this completion handler, I am trying to set the value of a simple NSTextField to the result of API. However, I am getting this error: Instance member 'currentTemp' cannot be used on type 'WeatherView'

Any idea what is wrong?

class WeatherView: NSViewController {

    var weather:Weather?

    @IBOutlet weak var currentTemp: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.

        WeatherFetcher.fetchCurrent(currentWeatherCallback)

    }

    override var nibName : String{
        return "WeatherView"
    }

    var currentWeatherCallback =
    {
        (weather: Weather?) in

        currentTemp.stringValue = weather?.updatedTime
        // Instance member 'currentTemp' cannot be used on type 'WeatherView'

    }


}
Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124

1 Answers1

3

You don't have access to the instance scope when initialising properties, you can only access the static context.

Try this:

var currentWeatherCallback: Weather? -> Void { return
    { (weather: Weather?) in
        self.currentTemp.stringValue = weather?.updatedTime
    }
}
marius
  • 2,077
  • 2
  • 16
  • 15
  • Make sure to add `[unowned self]` to this closure. Otherwise it's a reference cycle. – Rob Napier Jan 08 '16 at 17:02
  • Cool, this works. I am new to swift. Can you tell me what is the difference between your code and mine. currentWeatherCallback is ultimately a var in both the case and I understand its type has to be a closure. – Madhur Ahuja Jan 08 '16 at 17:10
  • @MadhurAhuja, your code defines a regular property and initialises it in a static context, while the code that I posted defines a ***computed property***, note the missing `=` operator. Computed properties's blocks are evaluated each time they're accessed and have access to the instance scope. – marius Jan 08 '16 at 17:17
  • actually @RobNapier, I believe that wouldn't have created a reference cycle. The instance does not hold a reference to that block that captures `self`. – marius Jan 08 '16 at 17:42