Swift 5.7: implementing Conforming Custom Struct to Sequence Protocol When Using Nested Dictionaries
I need help solving I'm prototyping a solution and I'm working on a project and hit a roadblock... I'm trying to create a custom struct that conforms to the `Sequence` protocol in Swift 5.7, but I'm running into issues when attempting to iterate over a nested dictionary structure. My goal is to generate a flat array of values, but the implementation seems to be causing a crash. Below is the relevant code: ```swift struct MyCustomStruct: Sequence { var data: [String: [String]] func makeIterator() -> some IteratorProtocol { return MyIterator(data: data) } } struct MyIterator: IteratorProtocol { var data: [String: [String]] var outerKeyIterator: Dictionary<String, [String]>.Keys.Iterator var innerIterator: [String].Iterator? init(data: [String: [String]]) { self.data = data self.outerKeyIterator = data.keys.makeIterator() self.innerIterator = nil } mutating func next() -> String? { if let inner = innerIterator { if let innerValue = inner.next() { return innerValue } else { innerIterator = nil } } guard let outerKey = outerKeyIterator.next() else { return nil } innerIterator = data[outerKey]?.makeIterator() return next() // Recursively call next() again after setting innerIterator } } ``` When I try to iterate over `MyCustomStruct`, like this: ```swift let sampleData: [String: [String]] = [ "fruits": ["apple", "banana"], "vegetables": ["carrot", "lettuce"] ] let myStruct = MyCustomStruct(data: sampleData) for item in myStruct { print(item) } ``` I get a runtime crash with the message: `Unexpectedly found nil while unwrapping an Optional value`. I've tried debugging by adding print statements to track the flow, but I need to seem to identify where the nil value is coming from. I checked the dictionary structure, and it looks fine. Any ideas on how to resolve this or if there's a better way to implement the `Sequence` protocol in this case? My development environment is Windows. This is my first time working with Swift stable. Any suggestions would be helpful. Is there a better approach? I'm coming from a different tech stack and learning Swift. Any pointers in the right direction? Thanks for taking the time to read this!