I am trying to get myself going with swiftUI. I was playing with the code below and trying to get the print() to work to see some variables during runtime in the preview window. Unfortunately it won't run once I add the print(), I get an Expected Declaration flag. Any info on using print() would be great as I have spent a few hours wondering around Google looking for answers with no luck so far.
import SwiftUI
struct ContentView : View {
@State var username: String = ""
let word1 = "Username"
let word2 = "Password"
print()
var body: some View {
VStack(alignment: .leading) {
Text("Login")
.font(.title)
.multilineTextAlignment(.center)
.lineLimit(nil)
Text("Please")
.font(.subheadline)
HStack(alignment: .center, spacing: 10) {
Text("Username: ")
TextField($username, placeholder: Text("type something here..."))
.textFieldStyle(.roundedBorder)
}
HStack(alignment: .center, spacing: 10) {
Text("Password: ")
TextField($username, placeholder: Text("type something here..."))
.textFieldStyle(.roundedBorder)
}
}.padding()
}
}
In SwiftUI, views are created inside the definition of a structure and then initialized when an instance is created from that definition, therefore, you can't execute code anywhere you want, you can only do it from inside the structure's methods or closures. For instance, if you look at your code, you tried to call the print() function in the place were the properties of the structure and its methods are defined. This is not allowed. If you want to execute code when the instance of that structure is created, you have to define the structure's initializer:
import SwiftUI
struct TestView : View {
let myvar = 150
init() {
print("myVar: \(myvar)")
}
var body: some View {
Text("Hello World!")
}
}
The body property is a computed property which value is defined by a closure, so you can use print() inside that closure. The problem is that closures know what value to return when they only have one statement, but if there are more than one statement, you have to specify what should be returned with the return keyword. In the following example I print a message but I specify that I want the Text view to be the value returned by the closure.
import SwiftUI
struct TestView : View {
let myvar = 150
var body: some View {
print("myVar: \(myvar)")
return Text("Hello World!")
}
}
Views like HStack or VStack are defined with a Content closure. I'm still not sure how those closures work, but they are expected to return a list of other views, so you can't call the print() function from there. If you want to print a value after a view was created, you can use the onAppear() modifier: This modifier applies to any view.
import SwiftUI
struct TestView : View {
let myvar = 150
var body: some View {
VStack {
Text("Hello World!")
.onAppear(perform: {
print("myVar: \(self.myvar)")
})
}
}
}
I imagine there are other ways, but those are the ones I'm using right now.