Appending an item to an optional array within a struct

Hello All, some background information first. I have the following struct:

Struct Category: Identifiable, Codeable, Hashable { var id: UUID var name: String var subCategory: [Category]? }

var categories: [Category]

There is no limit how many levels deep the subcategory can be. The user is essentially creating a hierarchical data filing system.

Given that the number of subCategory levels is unlimited, I am recursing over the subcategories to find the correct level at which to insert the newCategory.

The recursive function to add category is declared as:

func recursiveAddCategory(newCategory: Category, subCategoryOf: inout [Category]?)

you will note that I am trying to pass the subCategory as a reference (using inout), so that I can add to the original

and the function is called as recursiveAddCategory(newCategory, &categories.subCategory!)

the actual append statement within the recursiveAddCategory function is:

categories.subCategory?.append(newCategory)

I am encountering no errors but also find that the newCategory is not being added to the categories array.

Any help or guidance appreciated.

Thanks

Answered by VeeBee in 793051022

Hi Quinn, the issue has been resolved. Realised that I was trying to append to an uninitialised optional array. I was able to resolve by checking if the optional array was nil and if so, instead of appending, I initialised the array with the new data.

Can you post the code that you’re currently using? Ideally this would be a single code snippet that I can actually run. Also, use a code block (delimited with triple backquotes) so that the code renders nicely.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Hi Quinn, the issue has been resolved. Realised that I was trying to append to an uninitialised optional array. I was able to resolve by checking if the optional array was nil and if so, instead of appending, I initialised the array with the new data.

Appending an item to an optional array within a struct
 
 
Q