I'm a starter for Swift. Recently I met a problem with structure. Can anybody help me?

What does the warnning suppose to mean? I don't quite get what's wrong with my codes.

struct RunningWorkout {
    var distance: Double
    var time: Double
    var elevation: Double
    
    func postWorkoutStats()  {
        print(distance, time, elevation)
    }
}

let kkkk = RunningWorkout(distance: 444, time: 3.45, elevation: 9.89)
var gg = kkkk.postWorkoutStats()

In line12 the compiler complaint is "Variable 'gg' inferred to have type '()', which may be unexpected" What does it mean? Anybody knows that? Thanks😂

Accepted Answer

When you write:

     var gg = kkkk.postWorkoutStats()

you copy the func result into gg

You have defined RunningWorkout as not returning value.

In fact, it returns a result which is 'void', which is equivalent to ().

hence gg is of type void (i.e ())

So

     let kkkk = RunningWorkout(distance: 444, time: 3.45, elevation: 9.89) 
     var gg = kkkk.postWorkoutStats() 
     print(gg)

gives on console:

444.0 3.45 9.89

()


The compiler asks you if that's what you want.

What do you intend to do with gg ?

If you just want to run the func, write:

kkkk.postWorkoutStats()


If you change func to return a result


    func postWorkoutStats() -> Bool {
        print(distance, time, elevation)
        return true
    }


Now:

     let kkkk = RunningWorkout(distance: 444, time: 3.45, elevation: 9.89) 
     var gg = kkkk.postWorkoutStats() 
     print(gg)

gives:

444.0 3.45 9.89

true


And warning is gone.

Oh I get it! You mean the function will actually return a result "()" and the "()" is of type "void", right? So was it because I didn't define the variable "gg" as type "void"? If so, the following should be correct

var gg:Void = kkkk.postWorkoutStats()

You mean the function will actually return a result "()" and the "()" is of type "void", right?

Right. In fact, () and Void are the same thing in Swift.


So was it because I didn't define the variable "gg" as type "void"? If so, the following should be correct

Yes, perfect, you got it, that will silent the warning.

Note than even before, it was correct, the compiler just wanted to warn you.


Wish you good continuation. Don't forget to close the thread by marking the correct answer.

Ok, thank you so much😄😄

I'm a starter for Swift. Recently I met a problem with structure. Can anybody help me?
 
 
Q