Home > database >  how can i pass a variable's value as a parameter to function?
how can i pass a variable's value as a parameter to function?

Time:10-25

struct ContentView: View {
    @State var theme: Int = 1
    var emojis = getEmojis(theme)

theme can not pass to the function.Cannot use instance member 'theme' within property initializer; property initializers run before 'self' is available i am not familiar to swift, when i code, i find that i can't pass a var's value to the function i wrote. plz help me. i can pass 1 or 2 or 3 to the function, but i can't pass a var's value to function.

CodePudding user response:

It depends on what you're trying to do :)

If you're trying to initialize emojis to the value of getEmojis, but their values will differ in the future (you want to modify emojis independently of the value of getEmojis), use lazy var

struct ContentView: View {
    @State var theme: Int = 1
    lazy var emojis = getEmojis(theme)
    // ...
}

If emojis should always hold the value of getEmojis, use a computed property, like @Raja Kishan pointed out

CodePudding user response:

Use computed property

var emojis: YourType {
    getEmojis(theme)
}

Currently, you are trying to initialize one emojis variable with another theme var at the time of initialization. You can't provide value for a second var property that depends on another var property.

  • Related