ios – How can I add a variable to my “Task” class model that will hold the product of a calculation?


I am trying to take the TimeInterval of the startTime and endTime, plus the timeAdjustment and hold it in a variable to use for filtering my tasks in a view by total time earned. Right now I am using a picker to filter by Task.name, Task.startTime and Task.endTime. I want to be able to filer by something like Task.earnedTime. Task.earnedTime would have to be the calculation listed previously. Here is the code for my model:


import Foundation
import SwiftData

@Model
class Task {
    var name: String
    var startTime: Date
    var endTime: Date
    var timeAdjustment: TimeAdjustment
    var customTimeAdjustment: TimeInterval // Custom time adjustment
    var customAdjustmentName: String

 
    init(name: String = "", startTime: Date = .now, endTime: Date = .now, timeAdjustment: TimeAdjustment = .none, customTimeAdjustment: TimeInterval = 0, customAdjustmentName: String = "") {

        self.name = name
        self.startTime = startTime
        self.endTime = endTime
        self.timeAdjustment = timeAdjustment
        self.customTimeAdjustment = customTimeAdjustment
        self.customAdjustmentName = customAdjustmentName
        
    }
    
}

enum TimeAdjustment: String, CaseIterable, Codable {
    case none = "None"
    case kidsWereThere = "Kids were there -30 minutes"
    case attentionDiverted = "Attention was diverted -15 minutes"
    case fellAsleep = "We fell asleep -15 minutes"
    case purelyKink = "It was purely kink -15 minutes"
    case custom = "Custom Entry"

    var adjustment: TimeInterval {
        switch self {
        case .none:
            return 0
        case .kidsWereThere:
            return -30 * 60
        case .attentionDiverted:
            return -15 * 60
        case .fellAsleep:
            return -15 * 60
        case .purelyKink:
            return -15 * 60
        case .custom:
            return 0 // Custom adjustment will be set separately
        }
    }  
    
}

I have tried using a function in my model and have tried doing the calculation where the user enters their Task information, but it has not worked. This is my picker code and I would like to add the Task.earnedTime as a filter parameter:

 Picker("Sort", selection: $sortOrder) {
                        Text("Newest")
                            .tag(SortDescriptor(\Task.startTime, order: .reverse))
                        
                        Text("Oldest")
                            .tag(SortDescriptor(\Task.endTime, order: .forward))
                        
                        Text("Name")
                            .tag(SortDescriptor(\Task.name, order: .forward))
                        
                    }
                    .pickerStyle(.inline)

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img