Home > Net >  Swift 5 how to map an array of objects
Swift 5 how to map an array of objects

Time:07-19

I am trying to remap an array of objects so that I can use the values in a react native callback

manager.swft

@objc func getDevices {
  let devices = customManager.endpoints
  print(devices)
}

// prints an array of endpoints like shown below:
// [Endpoint(name: "first", uniqueID: 39), Endpoint(name: "second", uniqueID: 28)]

How can I remap the output of devices so that it prints or can be used in a callback like show below

I need devices to print like shown below:

[name: "first", uniqueID: 39, name: "second", uniqueID: 28]

or 

[{name: "first", uniqueID: 39}, {name: "second", uniqueID: 28}]

Basically I need to print out the array of devices without the "Endpoint" prefixed

CodePudding user response:

You could use the Swift map(_:) function.

let devices = customManager.endpoints.map {
  { name: $0.name, uniqueID: $0.uniqueID }
}

CodePudding user response:

You need to add the type of the endpoints variable to your question. I gather it is of type Endpoint? So edit your question and show us the definition of EndPoint.

Let's say it's a struct:

struct Endpoint {
   let Name: String
   let uniqueID: Int
}

You could add an extension to the Endpoint type that makes it conform to CustomStringConvertible:

extension EndPoint: CustomStringConvertible {
    var description: String {
        return "{name: \(name), uniqueID: \(uniqueID)}"
    }
}

And then use something like this:

let descriptions = customManager.endpoints.map{$0.description}
   .joined(separator: ", ")
print((descriptions)
  • Related