0

I'm not sure but after setting a value in struct I'm getting nil when trying to read the variable:

struct MainStruct : Decodable{
    var array : [InternalArray]?
}

struct InternalArray : Decodable{
    var firstName : String?
    var lastName : String?
    var Number : Int?
}



var testing: MainStruct?

testing?.array![0].firstName = "TEST"

print("test value \(testing?.array![0].firstName!)")

prints nil

2
  • 2
    I'm not sure what you're attempting to do, it seems like some entry-level exercise, but it seems to me like you are missing some key knowledge. I would suggest grabbing Apple's e-book on Swift and start from chapter one. Commented Mar 22, 2018 at 17:12
  • InternalArray ... isn't an array? Commented Mar 22, 2018 at 17:52

3 Answers 3

6

First of all you are using too many optionals.

Three(!) issues:

  1. Testing is not initialized.
  2. InternalArray is not initialized.
  3. You cannot access an array with index subscription if there is no item at given index (causes an exception).

struct MainStruct : Decodable {
    var array = [InternalArray]()
}

struct InternalArray : Decodable {
    var firstName : String?
    var lastName : String?
    var Number : Int?
}

var testing = MainStruct()
testing.array.append(InternalArray())
testing.array[0].firstName = "TEST"

print("test value \(testing.array[0].firstName!)")
Sign up to request clarification or add additional context in comments.

1 Comment

Personally I would create and initialize the InternalArray instance and then add it to the array. It's kind of strange to append the empty InternalArray and then set the name indirectly.
4

You haven't initialised testing.

2 Comments

And then once that is fixed the code will crash for force-unwrapping array. And once that is fixed, the code will crash for accessing the non-existing element at index 0.
@rmaddy: It's the "initial" reason for the error I'd imagine. I could be wrong though in thinking it shouldn't be up to someone to fix the OP's entire script!
0

This should work

var testing: MainStruct? = MainStruct()
testing?.array = []
testing?.array!.append(InternalArray())
testing?.array![0].firstName = "TEST"

7 Comments

of course, testing should not be optional any more.
Better yet: var testing = MainStruct(). And then remove all of the ?.
@MikeT Of course your are free to accept any answer you wish but the answer by vadian is so much more helpful. That answer fully explains what all of your issues are and shows a much better way to fix them all. Please give that answer a serious review.
@rmaddy I tried vadian answer and it's not working I guess the problem that this answer also has testing?.array = []
But vadian answer properly initializes array right inside MainStruct. No need to do it manually every time.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.