简体   繁体   中英

'self' used before super.init call and property not initialized at super.init call

I'm trying to init an array of Int in my custom UIView:

var graphPoints:[Int]

required init?(coder aDecoder: NSCoder) {
    RestApiManager.sharedInstance.requestData() { (json: JSON) in
        for item in json[].array! {
            let n=item["n"].intValue
            print(n)
            if(n>=0) {
                self.graphPoints.append(n)
            }
        }
    }
    super.init(coder: aDecoder)
}

But int this row RestApiManager.sharedInstance.requestData() { i reiceved this error: 'self' used before super.init call

And at this row super.init(coder: aDecoder) the error: property self.graphPoint not initialized at super.init call

Swift requires all parameters to be initialized before calling super.init() . There are several ways to make this happen.

Declare graphPoints with an empty initializer like this:

var graphPoints:[Int] = []   or var graphPoints = [Int]()

You can also change the graphPoints to an Optional, like this:

var graphPoints:[Int]?

You can also leave the declaration alone, and just initialize it to an empty array before calling super.init()

You will also need to move your RestAPI call below your super.init call.

Hope this helps.

There are a few seperate issues here

The first related two you question being that you must call the super.init method before you reference self. Simply move this line to the beginning on the init method.

Unfortunately because you are preforming an asynchronous request this will still cause you problems as mentioned in the comments.

Also, note init?(coder aDecoder: NSCoder) is not intended for this use. Another issue is if you are requesting data from your API you should create a model object. As opposed to directly creating a UIView and then when you wish to display it to a user create a UIView from that model.

class GraphPointsModel {
  var graphPoints:[Int]

  init(graphPoints: [Int]) {
    self.graphPoints = graphPoints
  }

  class func retreiveGraphPoints(handler: (GraphPointsModel -> ())) {
    RestApiManager.sharedInstance.requestData() { (json: JSON) in
      //Error checking...

      //Create instance of GraphPointsModel
      let instance = GraphPointsModel(...)  

      //Call handler to do with as you wish with result
      handler(instance)
    }
  }

}

Maybe you must to do this:

super.init(coder: aDecoder)

put that before your requestData call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM