play the game twenty questions in swift

Here's a simple program that allows you to play the classic game of Twenty Questions in Swift. This program asks the user to think of an object, and then asks up to 20 yes-or-no questions in order to guess what the object is.

import UIKit

class ViewController: UIViewController {

    let questions = [
        "Is it an animal?",
        "Is it a type of food?",
        "Is it a plant?",
        "Is it larger than a car?",
        "Is it smaller than a pencil?",
        "Can it fly?",
        "Is it a household item?",
        "Is it found outdoors?",
        "Is it typically man-made?",
        "Is it a type of clothing?",
        "Is it round?",
        "Is it a type of vehicle?",
        "Is it a musical instrument?",
        "Is it a type of sports equipment?",
        "Is it typically used indoors?",
        "Is it a type of toy?",
        "Is it a type of technology?",
        "Is it a type of furniture?",
        "Is it a type of appliance?",
        "Is it a type of plant?"

    var currentQuestionIndex = 0
    var yesAnswers = [Bool]()

    let maxNumberOfQuestions = 20

    override func viewDidLoad() {
        // Do any additional setup after loading the view.
        askQuestion(index: currentQuestionIndex)

    func askQuestion(index: Int) {
        if index >= maxNumberOfQuestions {

        let alert = UIAlertController(title: "Question \(index + 1)", message: questions[index], preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
            self.currentQuestionIndex += 1
            self.askQuestion(index: self.currentQuestionIndex)

        alert.addAction(UIAlertAction(title: "No", style: .default, handler: { action in
            self.currentQuestionIndex += 1
            self.askQuestion(index: self.currentQuestionIndex)

        self.present(alert, animated: true, completion: nil)

    func showResult() {
        var guessedObject: String

        // Simple rule based decision making
        if yesAnswers[0] == true && yesAnswers[1] == true && yesAnswers[2] == true {
            guessedObject = "dog"
        } else if yesAnswers[1] == false && yesAnswers[2] == false && yesAnswers[6] == true {
            guessedObject = "chair"
        } else if yesAnswers[1] == true && yesAnswers[15] == true && yesAnswers[9] == false {
            guessedObject = "football"
        } else {
            guessedObject = "I don't know"

        let alert = UIAlertController(title: "Result", message: "I guess you were thinking of a \(guessedObject)", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
2727 chars
83 lines

This is just a simplified version of the game, but you can make it more complex by adding more questions and more elaborate decision-making rules.

gistlibby LogSnag