问题描述:

I am writing a struct in Swift:

struct LevelDictionary {

let kNumberOfSegments: Int = 10

static func loadLevelData() -> NSDictionary {

for var segmentNumber = 0; segmentNumber < kNumberOfSegments; ++segmentNumber {

//My code here

}

return dictionary

}

}

For some reason I get an error on compiling: Instance member 'kNumberOfSegments' cannot be used on type 'LevelDictionary'. What am I missing? I get the same error when I set up LevelDictionary as a Class.

网友答案:

The direct answer to your question is that you can't use a property in class scope.

A different answer is that you seem to want a static function that returns a dictionary after doing something a certain number of times; which is why you have kNumberOfSegments in the first place. But do you really need to have a variable for something that you aren't going to use again. Another way to do this is to have a default variable in your class method:

struct LevelDictionary {

    static func loadLevelData(numberOfSegments: Int = 10) -> NSDictionary {
        for segment in 0 ..< numberOfSegments {
            // your code here
        }
        return dictionary
    }
}

Now you can call the method without an argument to use the default

let dictionary = LevelDictionary.loadLevelData() // Will use 10 segments

Or you can use a parameter to override the default

let dictianary = LevelDictionary.loadLevelData(20) // Will use 20 segments
网友答案:

loadLevelData() is a static function which is called on "class" level

LevelDictionary.loadLevelData()

To use kNumberOfSegments in the static function it must be static as well

static let kNumberOfSegments: Int = 10
网友答案:

You can't use instance member variables/constants inside the static function. (In terms of Objective C you can't use instance member objects inside class function)

Either you should declare the kNumberOfSegments as static or make that function as non-static. I prefer the first option,

struct LevelDictionary
{
    static let kNumberOfSegments: Int = 10

    static func loadLevelData() -> NSDictionary
    {
        for var segmentNumber = 0; segmentNumber < kNumberOfSegments; ++segmentNumber
        {
            //My code here
        }
        return dictionary
    }
}
相关阅读:
Top