Sweeper
Sweeper

Reputation: 275125

What is an alternative way to convert from a tuple array type to a named tuple array type?

In Swift, [(String, Double)] and [(name: String, result: Double)] are not compatible! To convert between these to types, I can only change the type name, which is so brute force.

I mean, these two types are logically compatible, right? Just throw away the name and you get [(String, Double)]. Add the names and you get [(name: String. result: Double)].

For now, I can only loop through the array and add each item to the variable of the other type. Which is so many lines of code just to do this!

What is a more elegant way to convert between these two types?

Upvotes: 0

Views: 394

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236568

You can use map:

let tupleArray: [(String, Double)] = [("element A", 2.5),("element B", 5.0)]
let tuppleNamedArray: [(name: String, result: Double)] = tupleArray.map{($0,$1)}
tuppleNamedArray.first?.result   // 2.5

or also as suggested by vacawama:

let tuppleNamedArray = tupleArray.map{(name: $0, result: $1)}

Upvotes: 2

Related Questions