【问题标题】:Saving a generated word to an array/list of words when a button is pressed按下按钮时将生成的单词保存到单词数组/列表中
【发布时间】:2018-03-16 08:29:07
【问题描述】:

我敢打赌,这对你们大多数人来说都是一个非常简单的问题,所以我会很快。本质上,我的 Swift 应用程序会生成一个随机单词,我希望用户能够选择标记为 1 23 的按钮,然后将该单词保存到数组中的特定数字中。稍后(包括应用程序关闭后等)用户可以查看他们分配了数字的所有单词。我知道这涉及创建一个新类并将相应的数组放在那里,但我真的不知道从哪里开始,所以任何帮助都表示赞赏。对不起,如果这不是你想要的那么清楚,你可以说我对 Swift/编程很陌生。截至目前,我与这部分应用程序相关的只是按钮:

var chosenNumber : String = ""


@IBAction func chosenOne(_ sender: Any) {
    chosenDifficulty = "one"
}
@IBAction func chosenTwo(_ sender: Any) {
    chosenNumber = "two"
}
@IBAction func chosenThree(_ sender: Any) {
    chosenNumber = "three"
}

谢谢

【问题讨论】:

    标签: arrays swift xcode sorting


    【解决方案1】:

    在您的 ViewController 中创建一个 computedProperty,如果有新值则保存,并在您在 viewController 中的任何位置访问它时返回保存的值:

     var savedWords: [String: Any]? {
        set{
            guard let value = newValue else {
                UserDefaults.standard.removeObject(forKey: "SavedWords")
                UserDefaults.standard.synchronize()
                return
            }
            UserDefaults.standard.set(value, forKey: "SavedWords")
            UserDefaults.standard.synchronize()
        }
        get{
            return UserDefaults.standard.string(forKey: "SavedWords") as? [String: Any]
        }
    }
    

    还有一个字典,其中包含您要添加/删除的当前单词的键值对

    var currentWords: [String: Any]? = ["button1": "one","button2": "two","button3": "three"]
    

    现在,无论何时单击您的按钮,您都可以通过以下方式将您的特定单词添加到 currentWords 字典中,并与 currentButton 键关联:

    currentWords["button1"] = /*selectedValue from button*/
    

    指定后是否要保存那些 currentWords 就可以了

    self.savedWords = currentWords
    

    如果您想检索 savedWords 并将其分配给 currentWords,您可以这样做:

    self.currentWords = savedWords
    

    【讨论】:

    • 我认为 Array 不是解决他的问题的理想解决方案。据我了解,必须将随机词分配给被选中的按钮。理想情况下,应该使用 NSDictionary 对象来保存这些随机单词。
    • 好的,我试试。 BCI,我将如何将 NSDictionary 实施到此类问题中。谢谢你们俩
    • @mBlot2 我编辑了我的答案,它以前是一个数组。不,它使用 BCI 建议的字典
    • 当您说添加如下代码行时:currentWords["button1": /*selectedValue from button*/] 是否将其添加到按钮 1 的 IBAction 中?我试过这样做,但是当我尝试用用户按下另一个按钮时生成的随机生成的单词替换 /*selectedValue from button*/ 时,它会显示“表达式列表中的预期表达式”,即:currentWords["chosenEasy" : "(\randomWord)" ] 谢谢
    • @mBlot2 已编辑!!请检查
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2019-12-18
    相关资源
    最近更新 更多