I am learning SwiftUI and creating a very simple app where some Ints are inputted on one screen (Itemsheet
), a calculation is run in app.xcdatamodel
and they are outputted on ContentView
.
However, the computed value is driving me crazy. It always seems to show as 0. I'd love to hear if anyone has any ideas why?
Here is my code:
ItemSheet.swift
@Environment(\.managedObjectContext) private var viewContext
Stepper("\(days) days", value: $days)
Stepper("\(cost)€", value: $cost)
app.xcdatamodel
extension Pricing {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Pricing> {
return NSFetchRequest<Pricing>(entityName: "Pricing")
}
@NSManaged public var days: Int16
@NSManaged public var cost: Int16
public var costPerDay: String {
get {
if (self.cost > 0) {
let newValue = String(format: "%.0f", "Cost per day: \(cost) / \(days)")
return newValue
}
else {
return "add cost"
}
}
set {
self.costPerDay = newValue
}
}
}
ContentView.swift
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(entity: Clothing.entity(), sortDescriptors: [])
var clothing: FetchedResults<Clothing>
var body: some View {
ForEach(clothing) { item in
Text("Days: \(item.days)")
Text("Cost: \(item.cost)")
Text("Cost per Days: \(item.costPerDay)")
}
}
}
Both the other Text views (Text("Days: \(item.days)")
and Text("Cost: \(item.cost)")
) are working fine, so guessing I am making a rookie error in the core data model somewhere?
Thank you!
Change your string to
String(format: "Cost per day: %.0f", Double(cost / days))
"%.0f"
is for Float
or Double
you are dealing with Int16