-3

I want to convert all @AppStorage's to Int(or even to Float) value and after that multiply it. Or probably i should to convert salaryPh and hoursPm to Int values, but i also can't do it. I've tried to create function where i could change String to Int but it didn't help me

I think that i'm doing something wrong, tried to find the solution with same question and found only one, but it didn't help me(link)

import SwiftUI

struct HomeView: View {
    var body: some View {
        NavigationView {
            ExtractedView()
        }
    }
}

struct ExtractedView: View {
    @State var monthString = Date().getMonthString().lowercased().capitalized
    @State private var salaryPh: String = "" 
    @State private var hoursPm: String = ""
    @AppStorage("SALARY_KEY") var savedSalary = ""
    @AppStorage("HOURS_KEY") var savedHoursPm = ""
    
    var body: some View {
        ZStack {
            BackgroundView()
            CalendarView()
            
            RoundedRectangle(cornerRadius: 40)
                .frame(width: 225, height: 100)
                .foregroundColor(.blue)
                .offset(y: 190)
            
            VStack(alignment: .center, spacing: 13) {
                Text("Your netto-salary per hour")
                    .foregroundColor(Color.white)
                    .font(Font.system(size: 23, design: .rounded))
                    .fontWeight(.light)
                TextField("Salary", text: $salaryPh)
                    .frame(width: 100, height: 50)
                    .background(.black)
                    .opacity(0.5)
                    .foregroundColor(Color.white)
                    .multilineTextAlignment(.center)
                    .font(.system(.body, design: .monospaced))
                    .overlay (
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(Color.blue, lineWidth: 4)
                    )
                    .onChange(of: salaryPh) { salaryPh in
                        self.savedSalary = salaryPh
                    }
                    .onAppear {
                        self.salaryPh = savedSalary
                        print("Loaded: \(savedSalary)")
                    }
            }
            .offset(y: -150)
            
            
            VStack(alignment: .center, spacing: 13) {
                Text("Hours in this month")
                    .foregroundColor(Color.white)
                    .font(Font.system(size: 23, design: .rounded))
                    .fontWeight(.light)
                TextField("Hours", text: $hoursPm)
                    .foregroundColor(Color.white)
                    .frame(width: 100, height: 50)
                    .background(.black)
                    .opacity(0.5)
                    .multilineTextAlignment(.center)
                    .font(.system(.body, design: .monospaced))
                    .overlay (
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(Color.blue, lineWidth: 4)
                    )
                    .onChange(of: hoursPm) { hoursPm in
                        self.savedHoursPm = hoursPm
                    }
                    .onAppear {
                        self.hoursPm = savedHoursPm
                        print("Loaded: \(savedHoursPm)")
                    }
            }
            .offset(y: -20)
        
            VStack(spacing: 20) {
                Text("In \(monthString) i make:")
                    .foregroundColor(Color.white)
                    .font(Font.system(size: 23, design: .rounded))
                    .fontWeight(.light)
                                
            }
            .offset(y: 165)
        }
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}
Deniss
  • 9
  • 6
  • This link: https://stackoverflow.com/questions/67809798/swiftui-unable-to-convert-string-from-appstorage-into-int-also-while-updating-t – Deniss Feb 08 '23 at 15:28
  • Why is it a String in the first place? – lorem ipsum Feb 08 '23 at 15:36
  • @loremipsum If i change it to State private var salaryPh = Int(), then i get an errors in TextField(where $salaryPh - Cannot convert value of type 'Binding' to expected argument type 'Binding'), in .onChange (salaryPh - Cannot assign value of type 'Int' to type 'String'). It happens also for hoursPm. If i change it to AppStorage("SALARY_KEY") var savedSalary = Int() and the other code don't change at all(like in my question) then i get an error here self.savedSalary = salaryPh(Cannot assign value of type 'String' to type 'Int') – Deniss Feb 08 '23 at 15:52
  • Use Textfield with “value” instead of “text” as the argument. Then you can specify “.number” for the format – lorem ipsum Feb 08 '23 at 15:53
  • https://developer.apple.com/documentation/swiftui/textfield/init(_:value:format:prompt:)-3fh51 – lorem ipsum Feb 08 '23 at 15:57
  • Does this answer your question? [SwiftUI unable to convert string from Appstorage into Int. Also while updating the second view it is creating a new view after every every keystroke](https://stackoverflow.com/questions/67809798/swiftui-unable-to-convert-string-from-appstorage-into-int-also-while-updating-t) – Wolfgang Wilke Feb 08 '23 at 16:21
  • 1
    @popeinvestor no, probably not, i've tried to work with .self like in this post, but there was too errors, therefore i decided to create this post. Also i did like lorem ipsum said and now it works, thanks. – Deniss Feb 08 '23 at 16:26

1 Answers1

1

You can get rid of all the conversion by using TextField with value.

    TextField(
        "Double",
        value: $myDouble,
        format: .number
    )

This setup will work with Int too.

Once the TextField is compatible with numbers you can switch all the Strings to be the correct number type.

https://developer.apple.com/documentation/swiftui/textfield/init(_:value:format:prompt:)-3fh51

lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • So, how to do it with float/double? – Deniss Feb 08 '23 at 17:24
  • 1
    @Deniss the same way, `.number` is for all numbers, just type the variables in `@State` and `@AppStorage` – lorem ipsum Feb 08 '23 at 17:26
  • Yep, i did it with double. I'm trying to get value with 2 or 3 decimal numbers in the end and the 3 hours after i didn't found any solution, tried to do it with round, ceil. Want to multiply salaryPh and hoursPm. For example in salaryPh user write 10.56 and in hoursPm 2, i want to get 21.12. How to do it? – Deniss Feb 08 '23 at 19:14
  • @Deniss that is a separate question, if this one was answered please click on the green checkmark. you can try `.number.precision(.fractionLength(2))` to limit the `format` in the `TextField` – lorem ipsum Feb 08 '23 at 19:19