Can someone please explain why this code doesn't execute. I am trying to learn the different ways to write functions/structs etc, and the one that has me puzzled is when you are write a function outside of a struct and call it in the struct (such as this):
struct ContentView: View {
var body: some View {
print(referencePoint(refX: 10, typeX: 10))
}
}
func referencePoint(refX: Int, typeX: Int) -> Int {
return (refX * typeX)
}
CodePudding user response:
It appears that you have elected to write a SwiftUI app. SwiftUI is a DSL (a "domain-specific language") and the things you can do in certain contexts are very restricted.
In particular, in the body
of a View (such as your ContentView), which is actually a view builder initializer, the only thing you are allowed to do is list the view's subviews, and you must describe these using SwiftUI conventions (i.e. the subview instance followed by any modifier method calls, then the next subview instance followed by any modifier method calls, etc.).
You cannot say print
in such a context. The error you are getting is telling you that, in an extremely technical and somewhat opaque way.
It may be that, if you are learning Swift, you should have started with a so-called Storyboard app instead. Even there you cannot just say anything at all in any context — in particular, you can't put executable code at top level — but you will probably find it easier to play around with the Swift language.
Or, you could experiment in a Playground (though I do not recommend this).
Or, if your choice of a SwiftUI project was deliberate, you should start with Apple's splendid SwiftUI tutorials (but you should still learn the full Swift language).