I'm going through the eBook Intro to App Development with Swift by Apple and I am making the Rock, Paper, Scissors app in lesson 20.
This is the assignment that I got:
[...] Name the enum
Sign
. Add a calculated property to give the emoji that represents theSign
. [...] You need to be able to compare twoSign
instances to give aGameState
. For example, a player’s.rock
and the app’s.paper
would give you.lose
. Add an instance method toSign
that takes anotherSign
, representing the opponent’s turn, as a parameter. The method should return aGameState
based on a comparison between self and the opponent’s turn. [...]
The code that I wrote works but I feel like this can be done a lot cleaner. Maybe it's Xcode's indentation that looks a bit weird to me, maybe there's a better solution?
I'll start with GameState.swift (these 4 gamestates were given in the instructions):
import Foundation
enum GameState {
case start, win, lose, draw
}
And here's Sign.swift:
import Foundation
enum Sign {
case rock, paper, scissors
var emoji: String {
switch self {
case .rock: return "👊"
case .paper: return "✋"
case .scissors: return "✌️"
}
}
func beats(otherSign: Sign) -> GameState {
switch self {
case .rock: do {
if otherSign == .paper {
return .lose
} else if otherSign == .scissors {
return .win
}
return .draw
}
case .scissors: do {
if otherSign == .rock {
return .lose
} else if otherSign == .paper {
return .win
}
return .draw
}
case .paper: do {
if otherSign == .rock {
return .win
} else if otherSign == .scissors {
return .lose
}
return .draw
}
}
}
}
beats
toplayAgainst
or something else, since it implies a boolean return type \$\endgroup\$