目标:如果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
提前致谢
答案 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
中的字典替换为修改后的字典。