core-data - Core Data 计算属性总是返回 0
问题描述
我正在学习 SwiftUI 并创建一个非常简单的应用程序,其中一些 Ints 在一个屏幕上输入(Itemsheet
),运行计算app.xcdatamodel
并在ContentView
.
但是,计算值让我发疯。它似乎总是显示为 0。我很想知道是否有人知道为什么?
这是我的代码:
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
}
}
}
内容视图.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)")
}
}
}
其他 Text 视图 (Text("Days: \(item.days)")
和Text("Cost: \(item.cost)")
) 都工作正常,所以猜测我在某处的核心数据模型中犯了一个新手错误?
谢谢!
解决方案
将您的字符串更改为
String(format: "Cost per day: %.0f", Double(cost / days))
"%.0f"
是为了Float
或者Double
你正在处理Int16
推荐阅读
- javascript - JavaScript 设置密码 DIV 值不起作用
- mqtt - 如何从 msg.Payload 获取字符串并使用它?
- vector - 如何在 vhdl 中生成随机 Std_logic_vector?
- cmake - 如何以非交互方式配置 CMake 构建?
- php - 如何从 mySQL 数据库创建格式化的 Excel 列表?
- function - Lua - 如果不使用“self”关键字,我应该在表中定义函数时使用“:”吗?
- node.js - 测试我的 api 调用时连接 ECONNREFUSED 127.0.0.1:80
- php - n个逗号后的PHP换行
- java - 将值从 Firebase 添加到 RecycleView 适配器不会显示在应用程序中
- class - Haskell 类型类“输入实例上的解析错误”