Reputation: 39
I want to add random Int number in my variable I tried var playerCard = "card" + String(a)
also var playerCard = "card\(a)"
but I get the same error. btw im just a beginner learning basics.
every solution will be appericated <3
@State var a = Int.random(in: 1...10)
@State var playerCard = "card" + String(a)
Upvotes: 1
Views: 56
Reputation: 150605
To add some explanation of why you need a computed property:
in Swift you don't have to use self
when accessing properties except when the compiler requires it. Write out your declarations in full with self
@State var a = Int.random(in: 1...10)
@State var playerCard = "card" + String(self.a)
The problem is that self
in self.a
, doesn't exist yet. You cannot access self until all the objects properties have been initialised, and since playerCard
is a property, it cannot be initialised, so the object cannot be initialised.
Upvotes: 0
Reputation: 30318
You can't have executable code, like "card" + String(a)
, directly in the property declaration... unless you use a computed property.
So, you can replace @State var playerCard = "card" + String(a)
with something like this:
var playerCard: String { /// this is a computed property!
"card" + String(a)
}
Upvotes: 1