在Swift中从Dictionary中提取值

时间:2016-05-14 10:39:10

标签: swift dictionary

目标:如果text1中的输入与superDictionary中的值匹配,那么第二个字典(与匹配的那个值对应)将其值乘以num1中的数字值按下按钮1(我知道一口)

e.g。 if text1.text =“apple”(与superDictionary中的值匹配)(参见下面的代码),然后该匹配将我重定向到appleDictionary,当button1为button1时,其每个条目再乘以num1中的数字值(比如5)按压。

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

我的IBOutlets和IBActions如下:

Sub UsageExample()
    Const sequence = "HTH"
    Const samples = 100000

    MsgBox "Average: " & GetTossingAverage(sequence, samples)
End Sub

Function GetTossingAverage(sequence As String, samples As Long) As Double
    Dim expected&, tosses&, mask&, tossCount#, i&
    Randomize ' Initialize the random generator. '

    ' convert the [TH] sequence to a sequence of bits. Ex: HTH -> 00000101 '
    For i = 1 To Len(sequence)
        expected = expected + expected - (Mid$(sequence, i, 1) = "T")
    Next

    ' generate the mask for the rotation of the bits. Ex: HTH -> 01110111 '
    mask = (2 ^ (Len(sequence) * 2 + 1)) - (2 ^ Len(sequence)) - 1

    ' iterate the samples '
    For i = 1 To samples
        tosses = mask

        ' generate a new toss until we get the expected sequence '
        Do
            tossCount = tossCount + 1
            ' rotate the bits on the left and rand a new bit at position 1 '
            tosses = (tosses + tosses - (Rnd < 0.5)) And mask
        Loop Until tosses = expected
    Next

    GetTossingAverage = tossCount / samples
End Function

提前致谢

1 个答案:

答案 0 :(得分:1)

我建议您合并词典并制作一个真实的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
}

注意:

  • 第一个警卫语句从num textField中提取num1。如果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中的字典替换为修改后的字典。