UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Project 2 - Any way to make this code more elegant?

Forums > 100 Days of Swift

Hi all,

I've learned that good code is DRY (don't repeat yourself.) As you can see on the code below, a lot of repetitions.

//
//  ViewController.swift
//  Project 2
//
//  Created by Bader Bouta on 15/07/2020.
//  Copyright © 2020 Bader Bouta. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!
    @IBOutlet var button3: UIButton!

    var countries = [String]()
    var score = 0
    var correctAnswer = 0
    var questionsAsked = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        button1.layer.borderWidth = 1
        button2.layer.borderWidth = 1
        button3.layer.borderWidth = 1

        button1.layer.borderColor = UIColor.lightGray.cgColor
        button2.layer.borderColor = UIColor.lightGray.cgColor
        button3.layer.borderColor = UIColor.lightGray.cgColor

        countries += ["Estonia", "France", "Germany", "Ireland", "Italy", "Monaco", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"]

        title = countries[correctAnswer].uppercased()

        askQuestion()
    }

    func askQuestion(action: UIAlertAction! = nil) {

        countries.shuffle()

        button1.setImage(UIImage(named: countries[0]), for: .normal)
        button2.setImage(UIImage(named: countries[1]), for: .normal)
        button3.setImage(UIImage(named: countries[2]), for: .normal)

        correctAnswer = Int.random(in: 0...2)
        questionsAsked += 1
        title = "Guess country: \(countries[correctAnswer]) - Score: \(score)"

     }

    @IBAction func buttonTapped(_ sender: UIButton) {
        var title: String

        if sender.tag == correctAnswer { //Alert when correct
            title = "Correct"
            score += 1
            let acCorrect = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert)
            acCorrect.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(acCorrect, animated: true)
        } else { //Alert if wrong
            title = "Wrong"
            score -= 1
            let acWrong = UIAlertController(title: title, message: "\(countries[sender.tag]) is wrong unfortunatly.", preferredStyle: .alert)
            acWrong.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(acWrong, animated: true)
        }

        // Alert after 10 attempts
        if questionsAsked == 10 {
            let questionAc = UIAlertController(title: "10 done", message: "You've completed 10 questions of which \(score) are correct", preferredStyle: .alert)
            questionAc.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(questionAc, animated: true)
        }

//        var ac = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert)
//        ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
//        present(ac, animated: true)

    }

}

specifically this code:

 {
        var title: String

        if sender.tag == correctAnswer { //Alert when correct
            title = "Correct"
            score += 1
            let acCorrect = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert)
            acCorrect.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(acCorrect, animated: true)
        } else { //Alert if wrong
            title = "Wrong"
            score -= 1
            let acWrong = UIAlertController(title: title, message: "\(countries[sender.tag]) is wrong unfortunatly.", preferredStyle: .alert)
            acWrong.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(acWrong, animated: true)
        }

        // Alert after 10 attempts
        if questionsAsked == 10 {
            let questionAc = UIAlertController(title: "10 done", message: "You've completed 10 questions of which \(score) are correct", preferredStyle: .alert)
            questionAc.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(questionAc, animated: true)
        }

I'm sure there is a more clean way of writing three seperate ac controllers over and over again, right?

Thank you for reading!

3      

For the buttons you can also add them to array which would be computed property, this way you could customize them all in a loop.

As for the UIAlertController you can assign title and message depending on conditions and then use these variables at the end to present the alert.

3      

@nemecek-filip

Thanks for the reply! I Would love to know how such code would look like. Could you point me in the right direction?

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.