Question about a code

What can I do with this problem?

You need to put your for loop in a method of your ViewController. You can’t just have it at the top level of the object.

It’s again the same problem.
Which way can I solve?

What you show here compiled just fine for me. You could have something elsewhere in your code that is causing the problem.

It’s usually a good idea to post your actual code rather than a screenshot. It makes it easier for other posters to test your code and possible solutions to your problem without having to retype everything. Not only is that a pain, but it can introduce it’s own problems. Being able to copy/paste the offending code is much better.

You can fence your code with ``` backticks on the line before and the line after to format it nicely, like so:

    var a: Int = 40
    var b: Int = 25
    func f(a: inout Int, b: inout Int) {
        for i in 2...b {
            if a % i == 0 && b % i == 0{
                a /= i
                b /= i

Now I have another question.
What do these messages mean?

It means exactly what it says: You cannot initialize a property from another property. This is because those lines run before the class’ self has been set up, so the properties don’t exist yet.

You can solve this by using lazy var instead of let. The lazy keyword means the property won’t exist until the first time it’s used and the property has to be a var instead of a let because it’s value isn’t set at the time the class finishes initializing.

Another issue you will have with that code is that the tuple returned by GCD1 doesn’t have any named members, so you cannot access, e.g., gcd.x. Instead, you will have to use gcd.0, gcd.1, and gcd.2.


Have you followed a course on Swift basics which includes the rules and syntax, very basic Apps through to more complex Apps and methods? I get the impression that you have missed some basic details that means you are attempting to do things you cannot do.

1 Like

you can use function gcd or gcd2

That’s built-in functions which find a greatest common divisor?

it isn’t built-in function.
you could see the gcd and gcd2 function in both screenshot.

in gcd function use the return value and gcd2 function use result paramater as inout.

or you can do this