私は公式のスウィフトの本で辞書について読んできましたが、私はいくつかの問題に直面しています。はい、それはあなたが辞書のようないくつかの簡単なことを説明します。 check if the whole dictionary is empty
またはchange 1 value of 1 key
、またはremove 1 value of 1 key
である。私はに実行する問題を実証するために、私は少しのコードスニペットを持っている:それは、配列にし、本当に厄介な感じ、それが戻って辞書に持ち込むよりも、保存するよりも、辞書からのものを取るために持つすべてのSwift 4の辞書を複雑に変更する最もクリーンな方法は何ですか?
//: Dictionary Test
import UIKit
let mainDatabase = ["Albert Einstein": ["Alberts first quote",
"Alberts second quote",
"Alberts third quote"],
"Martin Luther King": ["Martins first quote",
"Martins second quote",
"Martins third quote"],
"Newton": ["Newton first quote",
"Newton second quote",
"Newton third quote"]]
var database = mainDatabase // for later use
func randomQuote(){
//Make an array from all authors
var authorArray = Array(database.keys)
//Pick an author from that array
let author = (authorArray[Int(arc4random_uniform(UInt32(authorArray.count)))])
//Make an array from the quotes belonging to the author we've picked
var quoteArray = database[author]!
let randomNumber = Int(arc4random_uniform(UInt32(quoteArray.count)))
//Pick a quote from that array
let quote = quoteArray[randomNumber]
print(quote)
print(author)
//Delete the chosen quote from the array
quoteArray.remove(at: randomNumber)
//Update the new array to the database
database.updateValue(quoteArray, forKey: author)
print(quoteArray)
}
for index in 1...6{
randomQuote()
}
だから、最初。私はこれを行う簡単な方法があるように感じる。
このコードは、randomQuote()
関数を呼び出すたびに生成されていない見積もりを生成しますが、辞書が順序付けされていないため、重大なエラーが発生することがあります。
私は辞書の周りに頭を浮かべることはできませんし、それらを扱う方法。 bazillion記事を読んだ後でさえ...誰かのヒントはありますか?
* "時には致命的なエラーが発生する:Index out of range"著者の引用配列が空になるとどうなりますか?* –