Razor
Razor

Reputation: 306

Error Working with Type Methods

Ok, I've been working out of Apple's Swift manual and came across this example. I typed it in and received a 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT) error on:

if level > highestUnlockedLevel { highestUnlockedLevel = level }

I went back and checked my work. I compared what I typed to the example in the book via TextWrangler, no differences. I then rebooted my machine, no luck, then went back to try it on Xcode 6 Beta release 7. Same error. In fact the code below was taken from the book. Can some one please try this and see if they receive the same error?

struct LevelTracker {
    static var highestUnlockedLevel = 1
    static func unlockLevel(level: Int) {
        if level > highestUnlockedLevel { highestUnlockedLevel = level }
    }
    static func levelIsUnlocked(level: Int) -> Bool {
        return level <= highestUnlockedLevel
    }
    var currentLevel = 1
    mutating func advanceToLevel(level: Int) -> Bool {
        if LevelTracker.levelIsUnlocked(level) {
            currentLevel = level
            return true
        } else {
            return false
        }
    }
}

class Player {
    var tracker = LevelTracker()
    let playerName: String
    func completedLevel(level: Int) {
        LevelTracker.unlockLevel(level + 1)
        tracker.advanceToLevel(level + 1)
    }
    init(name: String) {
        playerName = name
    }
}

var player = Player(name: "Argyrios")
player.completedLevel(1)
println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")

Upvotes: 0

Views: 108

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

highestUnlockedLevel defined as static therefore change line

highestUnlockedLevel = level

to:

LevelTracker.highestUnlockedLevel = level

Playground

struct LevelTracker {
    static var highestUnlockedLevel = 1

    static func unlockLevel(level: Int) {
        if level > highestUnlockedLevel {
            LevelTracker.highestUnlockedLevel = level
        }
    } 
}    

LevelTracker.unlockLevel(5)

Upvotes: 1

Related Questions