簡體   English   中英

在Swift中從字典中的數組獲取值

[英]Get values from a Array in a Dictionary in 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] ...”行中,得到了錯誤線程1:信號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,因此這就是為什么它崩潰了。

抱歉打擾你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM