arrays - 从 Swift 字典中的数组获取值

标签 arrays swift dictionary

我的目标是拥有一个包含(除其他外)数组的字典,并能够获取该数组的值。

var total: Int = 0;
let dice:[NSTextField:NSArray] = [
        d4Amount:[d4OE, 4],
        d6Amount:[d6OE, 6],
    ];

for (die, dieArray) in dice
{
    let button:NSButton = dieArray[0] as! NSButton;
    let num:Int = dieArray[1] as! Int;
    total += DoRoll(die, oe: button, max: num);
}

在上面的“let button:NSButton = dieArray[0]...”行中,出现错误 Thread 1: signal SIGABRT 并且程序失败。 首先我只有一行:

total += DoRoll(die, oe: dieArray[0] as! NS Button, max: dieArray[1] as! Int);

这两者都不起作用(很明显),但是当我这样做时,它起作用了......

total += DoRoll(d4Amount, oe: d4OE, max: 4);

它工作得很好。

有什么想法吗?

函数 DoRoll 看起来像这样(应该不相关):

private func DoRoll(amount: NSTextField, oe: NSButton, max: Int) -> Int
{
    let nrRolls: Int! = Int(amount.stringValue);
    var total: Int = 0;
    if(nrRolls != nil && nrRolls != 0)
    {
        OutputText.string = OutputText.string! + "Now rolling d" + String(max) + ": ";
        for(var i: Int = 0; i < nrRolls; i++)
        {
            var randomNr: Int, specialMax: Int;
            var textStr: String = "";

            specialMax = max;
            if(max >= 100)
            {
                if(max > 100)
                {
                    specialMax = 995;
                }
                else if(max > 99)
                {
                    specialMax = 95;
                }
                else
                {
                    specialMax = max - 1;
                }
            }

            repeat
            {
                randomNr = Int(arc4random_uniform(UInt32(max))) + 1;
                total += randomNr;
                if(textStr != "") { textStr = textStr + "+"; }
                textStr = textStr + String(randomNr);
            } while(oe.state == NSOnState && randomNr >= specialMax)

            OutputText.string = OutputText.string! + textStr + " ";
        }
        OutputText.string = OutputText.string! + "\n";
    }

    return total;
}

最佳答案

我现在知道我做错了什么了。

这根本不是上面代码中的错误,而是项目中项目的命名错误。我在 View 中的同一个项目中有几个不同的 D4Amount,这就是它崩溃的原因。

抱歉打扰您。

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

相关文章:

ios - 在SwiftUI中点击Button时获取Tag值

swift - 在 SwiftUI 中出现 View 时禁用动画

python - 如何处理空字典值

c++ - 缺失项目最终数组列表

c++ - 我怎样才能找到这个数组中的最高值和最低值?

xcode - 库未加载 : @rpath/libswiftCore. dylibon 设备

c# - C# 如何处理字典项上的锁定?

python - 在 python 中是否有相当于 'map' 的就地等效项?

ruby-on-rails - 用于提交作为字符串传递的数组的 Rails 5 表单

c++ - 将一种类型的数组转换为另一种类型