SwiftUI 将字段条目存储为双精度或整数

SwiftUI Storing field entry as a double or integer

我正在尝试将用户的文本字段条目存储为数字,以便更容易在公式中使用。我以为我把它存储为一个字符串是很圆滑的,但现在在数学公式中使用输入正成为一个真正的痛苦。应该注意的是,这些字段条目当前作为字符串实体存储在 CoreData 中。

这是我的一个领域的 MRE:

import SwiftUI

struct EntryMRE: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @State private var showingResults: Int? = 1
    
    @FocusState private var isTextFieldFocused: Bool
    @State var isDone = false
    
    @State var isSaving = false //used to periodically save data
    @State var saveInterval: Int = 5 //after how many seconds the data is automatically saved

    //DataPoints Chemistry
    @State var potassium = ""
  
    
    var body: some View {
        List {
            Section(header: Text(" Chemistry")) {
                Group {
                    HStack {
                        Text("K")
                        + Text("+")
                            .font(.system(size: 15.0))
                            .baselineOffset(4.0)
                        Spacer()
                        TextField("mEq/L", text: $potassium)
                            .focused($isTextFieldFocused)
                            .foregroundColor(Color(UIColor.systemBlue))
                            .modifier(TextFieldClearButton(text: $potassium))
                            .multilineTextAlignment(.trailing)
                            .keyboardType(.decimalPad)
                        if let numberValue = Double(potassium) { // Cast String to Double
                            if (3.5...5.5) ~= numberValue {
                                Image(systemName: "checkmark.circle.fill")
                                    .foregroundColor(Color(UIColor.systemGreen))
                            }
                            else {
                                Image(systemName: "exclamationmark.circle.fill")
                                    .foregroundColor(Color(UIColor.systemRed))
                            }
                        }
                    }
                }
            }
        }
    }
}
                

虽然没有专门使用 $potassium 值,但这是我目前必须为公式做的事情:

import SwiftUI

struct ResultView: View {
    @Binding var isDone: Bool
    var EV: EntryView
    
    let decimalPlaces: Int = 2
    
    var body: some View {
        List {
            Section(header: Text("Formula")) {
                HStack {
                    Text("Corrected CO2")
                    Spacer()
                    Text("\(1.5 * (Double(EV.hCo3) ?? 0) + 8, specifier: "%.\(decimalPlaces)f")")
                }

如果您希望 @State var potassiumDouble 类型,您可以为 TextField.

使用不同的初始值设定项
@State var potassium = 0.0

TextField("mEq/L", value: $potassium, format: .number)

当然,您需要将 CoreData 模型更改为 Double 类型,但我认为这首先应该是 Double