0
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.

2 Answers2

1

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

Pastre
  • 684
  • 8
  • 17
-1

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.

Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
  • thanks, it works. and i wonder if you are happy to tell me reason or give me some url about swift. thanks again, sincerely. – YinY Huang Oct 24 '21 at 12:04
  • @YinYHuang added some info. you can also check from here https://stackoverflow.com/a/25856755/14733292 – Raja Kishan Oct 24 '21 at 12:12