Instance member cannot be used on type

后端 未结 8 1879
遥遥无期
遥遥无期 2020-11-29 04:13

I have the following class:

class ReportView: NSView {  
    var categoriesPerPage = [[Int]]()
    var numPages: Int = { return categoriesPerPage.count }
}
<         


        
8条回答
  •  一整个雨季
    2020-11-29 04:49

    Your initial problem was:

    class ReportView: NSView {
      var categoriesPerPage = [[Int]]()
      var numPages: Int = { return categoriesPerPage.count }
    }
    

    Instance member 'categoriesPerPage' cannot be used on type 'ReportView'

    previous posts correctly point out, if you want a computed property, the = sign is errant.

    Additional possibility for error:

    If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)

    class ReportView: NSView {
      var categoriesPerPage = [[Int]]()
      var numPages: Int = { return categoriesPerPage.count }()
    }
    

    Instead of removing the =, we add () to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)

    However, the exact same error occurs:

    Instance member 'categoriesPerPage' cannot be used on type 'ReportView'

    The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy. It will not be executed until the value is accessed.

    class ReportView: NSView {
      var categoriesPerPage = [[Int]]()
      lazy var numPages: Int = { return categoriesPerPage.count }()
    }
    

    now the compiler is happy!

提交回复
热议问题