skip to Main Content

I am trying to use @AppStorage to read/save a value and calculate something with it, but I am failing to call a function within my ContentView. Example:

Helper.swift

func powerized(x: Decimal) -> Decimal {
    let powerized: Decimal  = pow(x, 3) * 6.25
    return powerized
}

ContentView.swift

import SwiftUI

struct ContentView: View {
  @AppStorage(StorageKeys.sourcePower.rawValue) var sourcePower = 15

  var body: some View {
     VStack {
         Text(powerized(x: sourcePower))
     }
   }
}

With this implementation, I get Initializer 'init(_:)' requires that 'Decimal' conform to 'StringProtocol'.

If I put a

var myValue: Decimal = powerized(x: sourcePower)
Text(myValue)

I get a conversion error Cannot convert value of type 'Int' to expected argument type 'Decimal'. This probably is because of the variable not defined as Decimal but even making that change I then get
Cannot use instance member 'age' within property initializer; property initializers run before 'self' is available.

I am getting quite mad with this. Is there any change to make it working without creating a new class with ObservableObject ? The AppStorage already solves for updating the UI every time it changes.
I think, as a workaround, in theory I can precalculate what I want with my function as store it as well as the source value, but it does not make any sense.

2

Answers


  1. It has nothing to do with @AppStorage. Your powerized function returns a decimal, and you are trying to use is in a Text(). Text() requires a String. You can do:

      var body: some View {
         VStack {
             // Use .description which returns a String
             Text(powerized(x: sourcePower).description)
         }
       }
    

    Either of those will make it a String.

    Login or Signup to reply.
  2. Because decimals are formatted differently in different countries (e.g. some use comma as a decimal point) you have to use a formatter and there is a new convenience API for that:

    Text(powerized(x: sourcePower), format: .number)
    

    This way the label will also update automatically if the region settings change.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search