I have created a simple dictionary:
let quotes: NSArray = ["hello", "ola", "hi"]
Then I randomly access the strings in this dictionary with the following code:
let range: UInt32 = UInt32(quotes.count)
let randomNumber = Int(arc4random_uniform(range))
let QuoteString = quotes.objectAtIndex(randomNumber)
self.resultLabel.text = QuoteString as? String
Since I would ultimately like aloft of items in my dictionary, I should create a .plist file and called it "Quotes.plist" - it will be easier to manage a dictionary of many strings.
How can I write a simple code so as to randomly access strings within my .plist?
Amended Code:
func randomWord() -> String? {
guard let
path = NSBundle.mainBundle().pathForResource("Quotes", ofType: "plist"),
words = NSDictionary(contentsOfFile: path) as? [String:String] else { return nil }
let randomIndex = Int(arc4random_uniform(UInt32(words.values.count)))
return Array(words.values)[randomIndex]
My .plist file is "Quotes.plist".
A simple question (I apologise in advance), but how do I modify self.resultLabel.text = QuoteString as? String
so that the random quote now appears in my resultLabel.txt
?
Aucun commentaire:
Enregistrer un commentaire