Instance member cannot be used on type

后端 未结 8 1826
遥遥无期
遥遥无期 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 05:06

    Another example is, you have class like :

    @obc class Album: NSObject {
        let name:String
        let singer:Singer
        let artwork:URL
        let playingSong:Song
    
    
        // ...
    
        class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
            // ...
           return playingSong.lyric
        }
    }
    

    you will also get the same type of error like :

    instance member x cannot be used on type x. 
    

    It's because you assign your method with "class" keyword (which makes your method a type method) and using like :

    Album.getCurrentlyPlayingSongLyric(duration: 5)
    

    but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :

     // ...
    
     func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
            // ...
           return playingSong.lyric
     }
    
     // ...
    

    Now you're free to go.

    0 讨论(0)
  • 2020-11-29 05:06

    Just in case someone really needs a closure like that, it can be done in the following way:

    var categoriesPerPage = [[Int]]()
    var numPagesClosure: ()->Int {
        return {
            return self.categoriesPerPage.count
        }
    }
    
    0 讨论(0)
提交回复
热议问题