lurning too koad
lurning too koad

Reputation: 2974

Translating tuple to array?

I'm accessing a C language struct in my Swift project that stores data as a tuple and I want to iterate over it.

let tuple = (1, 2, 3, 4, 5)

AFAIK, I have two options. The first is to mirror the tuple so that I can map its reflection into an array:

let tupleMirror = Mirror(reflecting: tuple)
let tupleArray = tupleMirror.children.map({ $0.value }) as! [Int]

And the second option is to translate it into an array using manual memory management with something like an unsafe buffer pointer. From all that I've read, it's usually suggested to avoid the manual-memory route if possible and Mirror certainly appears to do that. Is mirroring a safe/reliable way to convert a tuple to an array? Or is there a better approach to translating the tuple into an array or even iterating over the tuple itself?

Upvotes: 3

Views: 2023

Answers (1)

user652038
user652038

Reputation:

Mirror is fiiiiiiiiiiiiine.

extension Array {
  init?<Subject>(mirrorChildValuesOf subject: Subject) {
    guard let array = Mirror(reflecting: subject).children.map(\.value) as? Self
    else { return nil }

    self = array
  }
}
  XCTAssertEqual(
    Array( mirrorChildValuesOf: (1, 2, 3, 4, 5) ),
    [1, 2, 3, 4, 5]
  )

  XCTAssertNil(
    [Int]( mirrorChildValuesOf: (1, 2, "3", 4, 5) )
  )

Upvotes: 4

Related Questions