Home > Mobile >  How to first 5 objects in Array with computed properties
How to first 5 objects in Array with computed properties

Time:12-22

My project uses an array of computed properties (hourly wages) from which I need to isolate/return only the first 5 objects (wages) in the array. (Note: I have simplified my code for the purpose of isolating this problem, but in so doing it may seem strange that this array is a computed property and not simply a variable. Please accept this oddity as it is necessary in my more complex, complete code.)

Research effort: enter image description here

Here is my code with a variety of approaches attempting to accomplish the same result:

class EarningsViewModel: ObservableObject {
    
    var catWageArray: [Double] {
        [81,156,162,166,169,173,177,181,185,192,277,280,282,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285]
    }

    var sliceCareerTest =  catWageArray.prefix(5)
    var sliceCareerTest2 =  catWageArray.prefix(upTo: 5)
    var sliceCareer: [Double] {
        catWageArray.prefix(5)}
    var sliceCareer2: [Double] {
        catWageArray.prefix(upTo: 5)}
    
    var n = 5
    var firstFiveSlice = catWageArray[0..<n]
    let firstFiveArray = Array(firstFiveSlice)

It seems to me that the sliceCareer computed property with the error "No 'prefix' candidates produce the expected contextual result type '[Double]'" may be the closest to the actual solution, but I don't understand why there the compiler cannot find prefix candidates.

CodePudding user response:

The proper way is prefix(5) but you have to create an array from the slice (aka SubSequence) and it must be a computed property.

On the other hand catWageArray can be a stored property

class EarningsViewModel: ObservableObject {
    
    var catWageArray: [Double] = [81,156,162,166,169,173,177,181,185,192,277,280,282,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285,285]
    
    
    var sliceCareer: [Double] {
        Array(catWageArray.prefix(5))
    }
...
  • Related