AndiAna
AndiAna

Reputation: 964

Calculating the max of a field across a set of data structures

I have a struct defining each data set:

struct TimeSeries: Codable, Hashable {
   var TradeDate: Date
   var Price: Double
}

and some dummy data conforming to this data type

var dummyData = [
TimeSeries(
TradeDate: "2021-01-01"
Price: 101.0),
TimeSeries(
TradeDate: "2021-01-02"
Price: 102.0),
TimeSeries(
TradeDate: "2021-01-03"
Price: 103.0),
TimeSeries(
TradeDate: "2021-01-04"
Price: 104.0)
]

in a SwiftUI View i want to calculate the max of the Prices in the Array.

struct ContentView: View {
   var data: [TimeSeries] = dummyData

   var body: some View {
       let maximum = data.Price.max()
       HStack {
              print(String(maximum))
       }
   }
}

This doesn't work. What am i doing wrong here?

I also tried to map the Price array to a new array like so

let pricearray = dummyData.map {$0.Price}
let pricemax = pricearray.max()

but that doesnt work either.

Upvotes: 0

Views: 40

Answers (4)

Duncan C
Duncan C

Reputation: 131436

There are two forms of the Array max method: max() and max(by:).

The simple max() version only works if the objects in the array conform to Comparable

The max(by:) method takes a closure that compares two elements, (similar to sorted(by:).

In order to find the max items in your array, you would use:

var body: some View {
   let maximum = data.Price.max {
       $0.Price < $1.Price
   }
   HStack {
          print(String(maximum))
   }
}

(Note that properties of structs should start with lower-case letters, so Price should be price.)

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 51993

Create a computed property for your ContentView that calculates the max price from the array

struct ContentView: View {
    var data: [TimeSeries] = dummyData
    var maxPrice: Double {
        data.map(\.Price).max() ?? 0.0
    }
   
    //rest of code...
}

Your properties should start with lowercase letters instead of uppercase so it should be tradeDate and price.

Upvotes: 1

AndiAna
AndiAna

Reputation: 964

func getMax (InputArray: [Double]) -> Double {
   return InputArray.max()!
}

and then in the body

let prices = data.map {$0.Price}
let maximum = getMax(InputArray: prices)

Upvotes: 0

gcharita
gcharita

Reputation: 8347

You can easily calculate the TimeSeries instance with the maximum price by using max(by:) function of Array, like this:

struct ContentView: View {
    var data: [TimeSeries] = dummyData

    var body: some View {
        let maximum = data.max { $0.Price < $1.Price }
        HStack {
            Text(maximum?.TradeDate ?? "nil")
        }
    }
}

Other than that I suggest you to follow Swift's API Design Guidelines, that state:

Follow case conventions. Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.

Upvotes: 0

Related Questions