0
import Foundation
import CoreData
import SwiftUI

struct dailyModel: Identifiable {
    let id: UUID =  UUID()
    let amount: Double
}


class DailyListModel: ObservableObject {
    @Published var dailys: [dailyModel] = []
    
    init() {
        getItems()
    }
    
    func getItems() {
        let newDailys = [
            dailyModel(amount: 0.0),
        ]
        dailys.append(contentsOf: newDailys)
    }

    func addItems(amount: Double) {
        let newItem = dailyModel(amount: amount)
        dailys.replaceSubrange(1, with: newItem)
    }
}

I get an error on line 'daily.replacesubrange' with red line under the first 'd' that says "Instance method 'replaceSubrange(_:with:)' requires that 'dailyModel' conform to 'Collection'"

Should I change dailyModel to also include Collection or change how I am using replaceSubrange?

Fausto IV
  • 5
  • 1

1 Answers1

0

There are two issues:

  1. requires that 'dailyModel' conform to 'Collection' means that the with parameter must be a collection like

    with: [newItem]
    
  2. The first parameter must be a range (Range<Int>), not a single Int, for a single item you can write

    replaceSubrange(1...1, 
    

If you replace only one item you could also write

func addItem(amount: Double) {
    let newItem = dailyModel(amount: amount)
    dailys.remove(at: 1)
    dailys.insert(newItem, at: 1)
}
vadian
  • 274,689
  • 30
  • 353
  • 361