PugBot

The sample project you’ll work with in this second half of the chapter is a PugBot. The PugBot is cute and friendly, but sometimes it gets lost and confused. As the programmer of the PugBot, it’s your responsibility to make sure it doesn’t get lost on the way home from your PugBot lab.

You’ll learn how to make sure your PugBot finds its way home, by throwing an error if it steers off course.

First, you need to set up an enum containing all of the directions in which your

PugBot will move:

enum Direction { case left case right case forward

}

You’ll also need an error type to indicate what can go wrong:

enum PugBotError: Error {

case invalidMove(found: Direction, expected: Direction) case endOfPath

}

Here, associated values are used to further explain what went wrong. With any luck, you’ll be able to use these to rescue a lost PugBot!

Last but not least, create your PugBot class:

class PugBot {

let name: String

let correctPath: [Direction] private var currentStepInPath = 0

init(name: String, correctPath: [Direction]) { self.correctPath = correctPath

self.name = name

}

func turnLeft() throws {

guard currentStepInPath < correctPath.count else { throw PugBotError.endOfPath

}

let nextDirection = correctPath[currentStepInPath] guard nextDirection == .left else {

throw PugBotError.invalidMove(found: .left,

expected: nextDirection)

}

currentStepInPath += 1

}

func turnRight() throws {

guard currentStepInPath < correctPath.count else { throw PugBotError.endOfPath

}

let nextDirection = correctPath[currentStepInPath] guard nextDirection == .right else {

throw PugBotError.invalidMove(found: .right,

expected: nextDirection)

}

currentStepInPath += 1

}

func moveForward() throws {

guard currentStepInPath < correctPath.count else { throw PugBotError.endOfPath

}

let nextDirection = correctPath[currentStepInPath] guard nextDirection == .forward else {

throw PugBotError.invalidMove(found: .forward,

expected: nextDirection)

}

currentStepInPath += 1

}

}

When creating a PugBot, you tell it how to get home by passing it the correct directions. The three movement methods cause the PugBot to move. If at any point the program notices the PugBot isn’t doing what it’s supposed to do, it throws an error.

Give your PugBot a test:

let pug = PugBot(name: "Pug", correctPath: [.forward, .left, .forward, .right])

func goHome() throws { try pug.moveForward() try pug.turnLeft() try pug.moveForward() try pug.turnRight()

}

Every single one of these commands must pass for the method to complete successfully. The second an error is thrown, your PugBot will stop trying to get home and will stay put until you come and rescue it.

results matching ""

    No results matching ""