Hello Guys, I'm an absolute beginner in swift. I need help with my code, not sure why its not showing the right output

A Steps struct has been created for you below, representing the day's step-tracking data. It has the goal number of steps for the day and the number of steps taken so far. Create a method on Steps called takeStep that increments the value of steps by one. Then create an instance of Steps and call takeStep(). Print the value of the instance's steps property before and after the method call.

struct Steps {

var steps: Int

var goal: Int

mutating func takeStep(){

steps+=1

}

}

var step=Steps(steps: 0, goal: 0)

print(step.takeStep())

This is because takeStep() does not return anything. If you meant to print the steps property, you can make takeStep() return steps.

I just did that but it's not working

Is this what you are trying to accomplish?

struct Steps {
    var steps: Int
    var goal: Int
    
    mutating func takeStep(){
        steps+=1
    }
    
}

var step = Steps(steps: 0, goal: 0)
step.takeStep()

print(step.steps)

Correct. I see the mistake, that I did. In terms of iOS development, are structures mostly used ?

There is a good WWDC video on this subject - watch Swift Modern API Design...

Cheers!

1 Like