포스트

Quizzler (3)

MVC Pattern의 image화


MVC Pattern은 별도로 정리를 해두는게 좋아보인다.


Quizzler(2)까지 했던 작업내역을 바탕으로 MVC패턴으로 Conversion해보자.

먼저 새로운 디렉토리를 만들어주자

MVC에 해당하는 총 3개의 디렉토리를 생성해주었다.

그리고 Model 디렉토리에 QuizBrain.swift파일을 하나 더 만들어 주었다.

QuizBrain.swift File에 다음과 같이 quiz Array를 옮겨주었다.

이미 값을 넣었기에, Initialize는 필요가없다.

questionNumber또한 옮겨 주었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Foundation

struct QuizBrain {
    let quiz = [
        Question(q: "A slug's blood is green.", a: "True"),
        Question(q: "Approximately one quarter of human bones are in the feet.", a: "True"),
        Question(q: "The total surface area of two human lungs is approximately 70 square metres.", a: "True"),
        Question(q: "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", a: "True"),
        Question(q: "In London, UK, if you happen to die in the House of Parliament, you are technically entitled to a state funeral, because the building is considered too sacred a place.", a: "False"),
        Question(q: "It is illegal to pee in the Ocean in Portugal.", a: "True"),
        Question(q: "You can lead a cow down stairs but not up stairs.", a: "False"),
        Question(q: "Google was originally called 'Backrub'.", a: "True"),
        Question(q: "Buzz Aldrin's mother's maiden name was 'Moon'.", a: "True"),
        Question(q: "The loudest sound produced by any animal is 188 decibels. That animal is the African Elephant.", a: "False"),
        Question(q: "No piece of square dry paper can be folded in half more than 7 times.", a: "False"),
        Question(q: "Chocolate affects a dog's heart and nervous system; a few ounces are enough to kill a small dog.", a: "True")
    ]
    
    var questionNumber = 0
    
}

그 이후 view Controller의 code를 아래와 같이 수정한다.

1
2
3
4
5
6
7
8
// before
let actualAnswer = quiz[questionNumber].answer
// change code
// after
quizBrain.checkAnswer(userAnswer: userAnswer)

quizBrain.checkAnswer(userAnswer)

checkAnswer의 경우 parameter를 표시하기 위해 userAnswer : ~~ 이렇게 표시를 하지만 보통은 parameter를 안보이고 그냥 매개변수만 넣는다.


다시 quizBrain.swift로 돌아와서,

1
2
3
4
5
6
7
8
func checkAnswer(_ userAnswer: String) {
        if userAnswer == quiz[questionNumber].answer {
            // User got it Right
        } else {
            // user got it Wrong
        }
        
    }

function checkAnswer에 관한 code를 위와 같이 수정해준다.

그렇다면 Viewcontroller에서

1
2
3
4
5
if userAnswer == actualAnswer {
            sender.backgroundColor = UIColor.green
        } else {
            sender.backgroundColor = UIColor.red
        }

위와 같이 답을 맞추었을때 background color를 바꾸었는데. 지금 관련된 code를 quizBrain으로 옮기고있다.

바로 위에있는 저 quizBrain에 backgroundcolor 변경에 관한 코드를 넣으려면 어떻게 해야할까?

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.