0
struct GroupStruct {
var groupName = " "
var groupAge= " "
var tests: [TestStruct] = []
}

struct TestStruct {
var desc= " "
var title= " "
}

Index out of range when GroupStruct.tests[0].desc = "abc" . why did that happen? thanks for helping.

3
  • because its empty? have you initialize GroupStruct.tests? have you add any TestStruct? Commented Aug 11, 2016 at 8:06
  • GroupStruct.tests[0].groupName = "abc" - I see three mistakes in this line. Try to rethink what are you doing and what are you need to achieve Commented Aug 11, 2016 at 8:06
  • how to initialise GroupStruct.tests? Commented Aug 11, 2016 at 8:07

2 Answers 2

1

You must initialize the GroupStruct. Then add the a new element on it.

import Foundation

struct GroupStruct {
    var groupName = " "
    var groupAge = " "
    var tests: [TestStruct] = []
}

struct TestStruct {
    var desc = " "
    var title = " "
}

// Creates a new instance of GroupStruct
var groupStruct = GroupStruct()

// Appends a new instance of TestStruct (will be at index 0)
groupStruct.tests.append(TestStruct(desc: "abd", title: ""))
Sign up to request clarification or add additional context in comments.

2 Comments

It seems it will start at index 1 instead of 0
Not really, the list is initialized but is empty, It will be added at index 0. Try print(groupStruct.tests[0]) and you'll see.
0

Do it this way:

var groupStruct = GroupStruct() // Declare groupStruct instance
var TestStructObj = TestStruct(desc: "abc", title: "abc") // Create TestStruct instance
groupStruct.tests.append(TestStructObj) // Append it to tests array

Tip - declare the array this way:

var tests = [TestStruct]()

1 Comment

It will not add on the GroupStruct array, only on the "tests" array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.