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.
CodePudding user response:
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
.