0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift]クイズアプリ 難易度に合致した問題を取得し、シャッフルしたあと数問ピックアップして返すやり方

Last updated at Posted at 2021-01-26

クイズをJSONファイルに作成し

Quiz.json
{
    "fourChoice": [
        {"question": "問題文", "answer": "答えの中身", "difficulty": "難易度", "commentary": "問題の解説"},
        {"question": "問題文", "answer": "答えの中身", "difficulty": "難易度", "commentary": "問題の解説"},
        {"question": "問題文", "answer": "答えの中身", "difficulty": "難易度", "commentary": "問題の解説"}
        以下続く
]

という具合に書いてあります。

[Quiz]の中にはクイズのArrayが入っています。

QuizBox.swift
func getQuestionsForGeneral() -> [Quiz] {
    return Array(getQuestionsByDifficulty(difficulty: 1).shuffled().prefix(10))
}

↑難易度を引数に受け取り、その問題リストを作成し、shuffled()をして問題をランダムにしてから、前の10個を取った上でArrayにして返す感じですね。


shuffled()
に関してはこちらの記事が参考になります。

https://capibara1969.com/2033/

つまり、shuffled()は、要素をシャッフルした配列を新たに生成します。

prefix()
に関していうと、最初からいくつ取り出すか、ということですね。今回は10問取得するので10としています。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?