Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'self' captured by a closure before all members were initialized

Tags:

Alright, so just to start off, heres my code:

import UIKit
import ForecastIO

class Weather {
    var temp: Float
    var condition: String
    var wind: Float
    var precip: Float

    init() {
        DarkSkyClient(apiKey: "<api key>").getForecast(latitude: Utils().getLat(), longitude: Utils().getLong()) { result in

            switch result {
            case .success(let currentForecast, _):

                self.temp = (currentForecast.currently?.temperature)!
                self.condition = (currentForecast.currently?.summary)!
                self.wind = (currentForecast.currently?.windSpeed)!
                self.precip = (currentForecast.currently?.precipitationProbability)!

            case .failure(let error):
                print(error)

            }

        }

    }

}

So my error comes up because I'm trying to initialize temp inside of the API call. I know this isn't the most reliable way of doing it but I'm trying to first get it to work.

The first error is:

'self' captured by a closure before all members were initialized

on the line DarkSkyClient(apiKey: "").getForecast(latitude: Utils().getLat(), longitude: Utils().getLong()) { result in

My second error:

Return from initializer without initializing all stored properties

on the second to last }

Now, obviously I'm not initializing right. I can't find the proper way to do what my end goal is though. Maybe I'm doing this entirely wrong?

like image 771
Charles Truluck Avatar asked Feb 22 '17 22:02

Charles Truluck


2 Answers

For me, it's because I didn't call super.init() in the initializer.

class AnObject: NSObject {
    override init() {
//        super.init()

        let _: ()-> (Void) = {
            print(String(describing: self))
        }
    }
}
like image 65
Winter Avatar answered Oct 03 '22 19:10

Winter


You have two options, declare the properties as optionals, or initialize them with a default value (this means they will be non-optionals)

var temp: Float?
var condition: String?
var wind: Float?
var precip: Float?

or

var temp: Float=0
var condition: String=""
var wind: Float=0
var precip: Float=0
like image 30
omarzl Avatar answered Oct 03 '22 19:10

omarzl