EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)。制作数据结构时出错

时间:2016-06-11 07:37:29

标签: swift

我正在用swift练习数组结构的数据结构。

我上了一堂课"学生"

并且有像display()和delete()

这样的函数

但是,该应用程序无效。

有一条错误消息

  
    

EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)。

  

我认为这个错误是关于"可选"问题

这是我的代码。

class student
{


var studentArray = [[String]?]()
var numberOfStudents : Int =  10;




func display()

{

    for (var i = 0; i < numberOfStudents   ; i++)

    {

        print("{");

        for (var j = 0; j < 2; j++)

        {

            print(studentArray[i]![j] + " ");

        }

        print("}");


    }

}


func  delete( value : String)

{

    var i = 0

    for ( i = 0; i < numberOfStudents   ; i++)


    {



        if (value == studentArray[i]![1])

        {

            break;

        }


    }


    if (i == numberOfStudents - 1 )

    {

        print("not found");


    }

    else

    {

        for (var k = i; k < numberOfStudents - 1  ; k++)

        {


            studentArray[k]![1] = studentArray[k+1]![1];
            studentArray[k]![0] = studentArray[k+1]![0];

}


        numberOfStudents--;

    }


}

}



var hello = student()


hello.studentArray = [["0","0ee"],["9","9ee", ]]
hello.display() // I have a error at this point

hello.studentArray

有人可以解释一下这对我来说是什么吗?

1 个答案:

答案 0 :(得分:1)

您的代码中存在多个错误。实际错误是由numberOfStudents变量引起的,该变量硬编码为10,即使该数组只包含2个元素。在studentArray.count循环中使用for,而不是10.然后阅读Swift手册。在此示例中,您不应该使用选项和C风格的for循环。

这是我怎么做的......

class Student {                         // Capitalise your classes
                                        // Unnecessary whitespace removed
    var studentArray: [[String]] = []   // No need for optionals here
    /*              
    var numberOfStudents : Int =  10;   // var is useless & wrong, also no need for semi-colon  
    */        
    func display() {
        /* A Swift-ier way to do this is
         for student in studentArray {
             print("{")
             for field in student {
                 print(field + " ")
             }
             print("}")
         }
         However, using indexing:
         */
        for i in 0 ..< studentArray.count {
            print("{")
            for j in 0 ..< studentArray[i].count { // Don't *know* this will be 2
                print(studentArray[i][j] + " ")    // Don't need semi-colons unless you want to put multiple statements on the same line
            }
            print("}")
        }
    }
    /* func delete() not used in question, so removed from answer */
}

var hello = Student()

hello.studentArray = [["0","0ee"], ["9","9ee", ]] // Note spurious (but not wrong) comma
hello.display()

hello.studentArray