Magic Eight Ball in Swift

“Magic Eightball” is a toy used for fortune-telling or seeking advice, which is shaped like a black ball with a small window that shows one of 8 possible answers. The user asks a yes-or-no question, then shakes the ball to reveal an answer, which could be “Yes”, “No”, “Ask again later”, or other responses.

It’s considered a novelty or party item and is often used for fun or as a conversation starter. While the toy has no actual supernatural or predictive powers, it remains a popular and iconic item to this day.

The structure of the code

The setup
  • First we set up a variable called playerName that stores the name of the player
  • Then we set up a variable called playerQuestion that stores the players question to the Magic Eightball
  • Then we create a variable called randomNumber that stores the code to genrates a random number between 1 and 8
  • Finally we setup a variable with an empty string that will contain the answer as soon as the randomNumber is defined
The control flow
  • Based on the number generated in randomNumber The control flow, here in the form of a switch statement prints out the answer to the console


// The setup

var playerName: String = ""
let playerQuestion: String = "Will it rain tomorrow?"
let randomNumber: Int = Int.random(in: 1...8)
let eightBall: String = ""

// The control flow

switch randomNumber {
  case 1:
    print("My answer is: 'Yes - definitely'")
  case 2:
    print("My answer is: 'Without a doubt'")
  case 3:
    print("My answer is: 'Reply hazy, try again'")
  case 4:
    print("My answer is: 'Ask again later'")
  case 5:
    print("My answer is: 'Better not tell you now'")
  case 6:
    print("My answer is: 'My sources say no'")
  case 7:
    print("My answer is: 'Outlook not so good'")
  case 8:
    print("My answer is: 'Very doubtful'")
    print("There must be an error somewhere")

// The output

print("\(playerName) ,your question is: '\(playerQuestion)'")

Leave a Reply

Your email address will not be published. Required fields are marked *