Place for calculations in SwiftUI

Hello, I'm completely new to Swift and SwiftUI and I'm currently trying to start some small test projects to understand the language, but I'm already stuck at the very beginning and couldn't resolve my problem with the help of Google so far.

I would just like to know, where in SwiftUI I can make some calculations, if needed?

For example, if I create a simple variable (var i = 1) in the ContentView.swift file after import SwiftUI, where exactly am I allowed to manipulate (i += 1) this variable?

If I try right after the initialization (before struct ContentView: View { ...) its says, that "Expressions are not allowed at top level".
If I try within the ContentView struct, but outside its "body" I get various error messages depending on the exact line as well.
If I try within the body part, I get the error message "Type '()' cannot conform to View".

So where on earth am I allowed to do anything with my created variable?

First, SwiftUI is not part of the Swift language, but, is an Apple private network for creating and manipulating GUI applications within the Apple ecosystem using Swift. Questions about Apple frameworks should be directed at Apple through the developer forums, Stack Overflow. There are also online books, tutorials that go into how to develop GUI applications.

You can also write a command line program that declares i, assigns it a value, and prints it, all within Swift itself using the language without having to get involved with GUI stuff right off the bat. In that situation, Swift is used just like C, C++, Fortran, Rust, Go, etc.. The Swift Programming Language reference guide provides all the features of the language (available through the Apple Book store and on

All depends on what you want to do.

1 Like

But isn‘t SwiftUI just another framework, that can be used within Swift code just like other frameworks for other purposes (Databases, Files, …) and should therefore work within the same logic of any other Swift program?

Apart from that, I of course want to use SwiftUI, so it wouldn‘t help me to write a line of code where i increase i by 1, if I then still have no idea how to do that when using SwiftUI?

The short answer is "no".

Are you working on an Apple platform and want to build a Graphical User Interface application? If no, then SwiftUI is useless to you. If yes, there is a whole background of material you have to master in order to even perform the simple task you've set yourself. If you search for "SwiftUI tutorial" on the Internet, you should find some tutorials on developing Apple GUI applications from scratch, tailored to beginners.

Again, SwiftUI is not part of open-source Swift. It is an Apple-private framework for building GUI applications on par with CoreData, Core Graphics, Core Animation, UIKit, AppKit, and the other components of the Apple application development ecosystem.

1 Like

There's a bit more to this than just the fact that SwiftUI is an Apple framework, not part of the Swift language.



SwiftUI is an example of a DSL, or "Domain Specific Language". It's similar in syntax to the Swift programming language, but it's for making declarations, not writing code.

Some of the syntax is similar to regular Swift code, and there are places in DSLs where you can actually invoke Swift code, but you can't just write arbitrary code, even something simple like i += 1.

SwiftUI is a DSL for declaring UIs. You might decide to use it in apps running on Apple platforms, but it's essentially different from writing normal code.

Yes, of course I'm working on an Apple and want to build programs with GUIs using Swift and SwiftUI. Is Swift really used outside of the Apple world (I'm aware, that other implementations exist, but I suggested, that they aren't really used very often)?

Thanks for the additional explanation. Unfortunately I haven't found out yet, how to link my Swift code (the increase of i by 1) to my SwiftUI (for example a text field showing the content of variable i).

Shouldn't something this fundamental and simple be really briefly explained as the very first thing (after syntax) in any SwiftUI tutorial?
After all, what sense makes a UI without logic?

In order to update content in a SwiftUI View you need to use the @State property wrapper, bind this to a variable in your SwiftUI View. Per this doc, and this one. Hope this helps! :slight_smile:

Edit: There is also this document that explicitly talks about managing UI state

I was going to suggest looking at some examples. You could try starting with tutorials here.

These are pretty much exercises in constructing UI, but they'll help show how code that relates to how information is shown fits into the overall SwiftUI picture.

This also is amazing ^ that entire stack of tutorials are great.

I'd highly recommend 100 Days of SwiftUI – Hacking with Swift! That's your best place to learn SwiftUI (free) if you're new – that's how I did it (and not that long ago in fact).

Thanks, the links can surely be helpful.
I think, my problem is located even before the use of states.

I meanwhile found, that I can make it work, if I place the calculation inside the body part of the View struct in SwiftUI, the upfront declaration of the initial variable ( var i = 1) can be pretty much at any place before that, but for the cases, where it doesn't work, the error message depends on the place where I declared the variable (after View body, after View struct, after imports).

What I don't understand now is, why I now can't change the original variable (i = i + 1), but need to declare a new one for the calculation (j = i + 1), because in the first case I get an error message ("self is immutable") if I want to show i in a text field, whereas showing j in the text field in the second case works perfectly?

Thanks, I've already seen the tutorial, but so far, it's not helpful for me to get an answer on how to display even a simple calculation (var i =1, i +=1, Text("(i)").

Thanks, I already came across the site as this is, where I got an overview of the most important clauses and data types in Swift.

The problem here is not the simplicity of the calculation, but the question of when you want to do that calculation.

When you do want to do that calculation? What should trigger it?

Well, here is a complete code.

import SwiftUI

struct Test: View {
    var i = 1
    var body: some View { // Error: "Type '()' cannot conform to 'View'"
        i = i + 1 // Error: "Cannot assign to property: Self is immutable"

I mean, this should be really simple, right? Nevertheless, I get the "Self is immutable" error followed by the "cannot conform to View" error.

If I create a new variable j with var j = i + 1 , for some reason it works? But I would like to know, how to make it also work with i or understand, why it doesn't work with i (which is a variable)?

And if I change the declaration of i to @State var i = 1 , the "immutable" error disappears, but the "cannot conform to View" error stays?

Unfortunately these diagnostics don't point you towards the actual issue: var body: some View implements View's requirement, which is marked @ViewBuilder, so that computed property is actually a @resultBuilder. That means it has difference syntax rules. To do the work you want, you need to be outside of a build. In SwiftUI that usually means in the action handler of a particular view, like Button, or something like onAppear or task. I suggest you go through 100 Days of SwiftUI, as mentioned before, to get familiar with these constructs and their limitations.

Thanks, so far, ViewBuilder, ResultBuilder etc. say nothing to me.

I understand independently of a specific language general concepts like variables, loops, interfaces etc., so I think it should be possible to work out the specifics for those kind of things for Swift on the road.

Apart from that, what you mean is, the amount of work it takes to understand basic concepts - I’m not talking about any deep dive with all kinds of details - of specifically Swift and SwiftUI (and all things needed to understand why my very basic 4 line program with nothing else than a declared variable, a simple calculation and a graphical output of the result doesn‘t work are definitely basic concepts of Swift from my point of view) are those 100 days from this course and no less?
And this course at least includes basic explanations of those and other basic concepts to understand what is going on in Swift and why, to be able to learn any additional details afterwards independently?

When you immediately jump into an advanced UI framework you're going to run into these issues. If you're completely unfamiliar with Swift, I suggest reading The Swift Programming Language and doing Hacking with Swift's 100 Days of Swift, which is a more gradual introduction to the language itself. The first 10 days or so of 100 Days of SwiftUI are also a language overview, so you could start there if you wanted. (These tutorials don't actually take 100 days, they're just organized that way.)

You didn't answer the question. :slight_smile:

The body property describes the structure of a SwiftUI View (it contains a Text view and nothing else), but says nothing about when it's displayed. Procedural code inside the body is meaningless because there's nothing to say when to increment i.

I want to emphasize that the code inside the body property is not executable Swift code as such, but syntax for the SwiftUI DSL.

So, when do you want to increment i?