-4

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)
}
  • 1
    Related: https://stackoverflow.com/q/69433485/1187415, https://stackoverflow.com/q/64678359/1187415, https://stackoverflow.com/q/56517813/1187415 – Martin R Nov 27 '22 at 17:29
  • 1
    Try `let _ = print(referencePoint(refX: 10, typeX: 10))` – koen Nov 27 '22 at 17:42
  • 2
    @koen That will get the code past the compiler, perhaps, but I believe it won't print anything. – matt Nov 27 '22 at 18:46
  • 2
    every `return` point in a `body` should produce a `View`, `print` is a `Void` not a `View`. You should look at the SwiftUI tutorials that apple provides – lorem ipsum Nov 27 '22 at 19:14

1 Answers1

4

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).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thanks, i was a couple of days into learning when i wrote the question. I am a few days further into the course now so i understand what you mean. I am a little surprised that my post got any downvotes though, it was a geniune question from someone who had just started learning (had i known what to search for on google at the time i would have done). Etiher way thanks for your answer though! – JasonFromLondon Dec 07 '22 at 18:55