I have the following class:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Compilation fails with the message:
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
What does this mean?
I kept getting the same error inspite of making the variable
static
. Solution: Clean Build, Clean Derived Data, Restart Xcode. Or shortcut Cmd + Shift+Alt+KFor anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)
eg.
Another example is, you have class like :
you will also get the same type of error like :
It's because you assign your method with "class" keyword (which makes your method a type method) and using like :
but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :
Now you're free to go.
Just in case someone really needs a closure like that, it can be done in the following way:
You just have syntax error when saying
= {return self.someValue}
. The=
isn't needed.Use :
if you want get only you can write
with the first way you can also add observers as
set
willSet
&didSet
allowing to use
= operator
as a setterYour initial problem was:
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)
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:
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 someone access the value.now the compiler is happy!