Home > Blockchain >  SwiftUI: ColorScheme and init()
SwiftUI: ColorScheme and init()

Time:02-24

im working on simple iOS app and there's a reason why I have to use init() section. for i.e.:

import SwiftUI
struct ContentView: View {
    @State var newName: String
    @Environment(\.colorScheme) private var colorScheme: ColorScheme
    init(){
        newName = "test"
    }
    var body: some View{
        VStack(alignment: .center) {
            TextField("Sample TextField", text: $newName)
        }
    }
}

everything works just fine until I add @Environment(\.colorScheme) private var colorScheme: ColorScheme

I instantly get quite strange error "Variable 'self.newName' used before being initialized"

what am I missing?

CodePudding user response:

There are two ways to declare properties inside Struct or a Class:

1- Optional Properties: These properties doesn't required initial value during initialisation of Struct or Class, we can declare it using question-mark on type: @State var newName: String?

2- Non-Optional Properties: These properties must required initial value during initialisation of Struct or Class, we can declare it like this: @State var newName: String

So in your case you are using Non-Optional property, so you must need to provide either a default value to your newName: @State var newName: String = "" or pass a value for newName in the constructor of your Struct: ContentView(newName: "Okeyman"), you don't need to add init(){ } because Struct will automatically do this for you.

import SwiftUI

struct ContentView: View {

    @State var newName: String
    @Environment(\.colorScheme) private var colorScheme: ColorScheme
    
    var body: some View{
        VStack(alignment: .center) {
            TextField("Sample TextField", text: $newName)
        }
    }
}

Call it like this

ContentView(newName: "Okeyman")

CodePudding user response:

For some reason, in this case you can initialise your @State parameter the way its mentioned in this answer

_newName = State(initialValue: "test")

  • Related