gpt4 book ai didi

swift - 在 Swift 中从字典中提取值

转载 作者:行者123 更新时间:2023-11-28 06:43:32 25 4
gpt4 key购买 nike

目标:如果 text1 中的输入与 superDictionary 中的值匹配,则第二个字典(与匹配的值对应)的值乘以 num1 中的数字值当按下 button1 时(我知道一口)

例如如果 text1.text = "apple"(与 superDictionary 中的值匹配)(请参见下面的代码),那么该匹配会将我重定向到 appleDictionary,当 button1 为按下。

问题:我不知道用什么语法来做这件事!

我的IBOutlets和IBActions如下:

@IBOutlet weak var text1: UITextField!

@IBOutlet weak var num1: UITextField!

var superDictionary = ["apple","banana"]

var appleDictionary = ["fibre": 1, "water": 2]

@IBAction func button1(sender: AnyObject) {}

提前致谢

最佳答案

我建议你结合你的字典并制作一个真正的superDictionary:

var superDictionary = ["apple": ["fibre": 1, "water": 2], "banana": ["potassium": 2, "water": 2]]

那么您的按钮操作将是这样的:

@IBAction func button1(sender: AnyObject) {
guard let num = Int(num1.text ?? "") else { return }
guard let text = text1.text else { return }
guard var dict = superDictionary[text] else { return }

for (key, value) in dict {
dict[key] = value * num
}

superDictionary[text] = dict
}

注意事项:

  • 第一个 guard 语句从 num1 文本字段中提取 num。如果 textField 是 nil nil 合并运算符 ?? 将它变成一个空的 String ,其中 Int 变成了 nil。如果有字符串可以成功转换为Int,则guard语句成功并将其赋值给num,否则函数返回。
  • 第二个guard 语句将text1.text 中的字符串分配给text 或者如果textField 为nil 则返回>.
  • 第三个guard 语句将正确的字典分配给dict(如果存在),如果不存在则返回。这个 guard 使用 var 而不是 let 因为我们将修改这个字典。
  • 循环通过提取 key/value 对并将 value 替换为 value * num 来修改字典。
  • 最后的作业用修改后的字典替换 superDictionary 中的字典。

关于swift - 在 Swift 中从字典中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com