Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix "Cannot assign value of type 'Int' to type 'State<Int>'" swift

I have

struct ContentView: View {
    @State var n: Int

    init() {
        _n = 3
    }

On the line with _n = 3, i get the error Cannot assign value of type 'Int' to type 'State<Int>' How do I fix this?

like image 478
jellyshoe Avatar asked Sep 18 '25 05:09

jellyshoe


1 Answers

The error is fairly self-explanatory. _n is of type State<Int> and you're trying to assign an integer to it.

You can create a State<Int> instance like so

_n = State(initialValue: 3)

but it's not clear why you're doing it. You should just assign the initial value directly:

@State var n: Int = 3
like image 125
New Dev Avatar answered Sep 19 '25 22:09

New Dev