ammoriz
ammoriz

Reputation: 29

How to get structured data in an array in Swift 3

Hi there I made this code as example :

struct myData{
var payments: Int!
var paymentDate : String!
var itemNumber : String!
              }

var myDataArray = [myData(payments:100, paymentDate: "10/10/2010", itemNumber: "1001"),
               myData(payments:200, paymentDate: "10/10/2010", itemNumber: "1002" ),
               myData(payments:500, paymentDate: "10/10/2010", itemNumber: "2001" ),
               myData(payments:400, paymentDate: "10/10/2010", itemNumber: "3210" ),
               myData(payments:150, paymentDate: "10/10/2010", itemNumber: "1234" ),]

What I'm asking for how could I get the results for a specific object for that structure Data. for Example If I want to print all the payments result or specific IndexPath

really I tried hard and I searched hard but without any clear answers

Upvotes: 0

Views: 104

Answers (2)

MrMage
MrMage

Reputation: 7487

If you only want to print the data, see PEEJWEEJ's answer. If you want an array of, say, all payments properties of the individual array entries, use

myDataArray.map { $0.payments }

which essentially means 'go through each element of myDataArray, execute element.payments on each of these elements, then build an array with the results'.

By the way, it seems like your properties are always available, i.e. never nil. In that case you don't need to add a ! at the end of the declaration, so

struct MyData {
  let payments: Int
  let paymentDate: String
  let itemNumber: String
}

would be sufficient.

Upvotes: 2

GetSwifty
GetSwifty

Reputation: 7746

print(myDataArray[0].payments) would print the first item's payments. (so 100)

If you want to print all of them, you could loop through it like so: myDataArray.forEach { print($0.payments) }

Upvotes: 1

Related Questions