随机访问 .plist 文件中的字典字符串值

Randomly accessing dictionary string values in a .plist file

我创建了一个简单的字典:

    let quotes: NSArray = ["hello", "ola", "hi"]

然后我用下面的代码随机访问这个字典中的字符串:

    let range: UInt32 = UInt32(quotes.count)
    let randomNumber = Int(arc4random_uniform(range))
    let QuoteString = quotes.objectAtIndex(randomNumber)
    self.resultLabel.text = QuoteString as? String

因为我最终希望我的字典中有很多项目,所以我应该创建一个 .plist 文件并将其命名为 "Quotes.plist" - 管理包含多个字符串的字典会更容易。

我如何编写一个简单的代码来随机访问我的 .plist 中的字符串?

修改后的代码:

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]

我的 .plist 文件是 "Quotes.plist"。

一个简单的问题(我提前道歉),但是我如何修改 self.resultLabel.text = QuoteString as? String 以便随机引用现在出现在我的 resultLabel.txt 中?

如果 你的 PLIST 被定义为字典那么这应该可以完成工作。否则请提供有关您的 PLIST 结构的模式详细信息。

func randomWord() -> String? {
    guard let
        path = NSBundle.mainBundle().pathForResource("Words", 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]
}