When it comes to calling a static function from a structure, should a member wise initializer be used?

struct RunningWorkout {

var distance: Double

var time: Double

var elevation: Double

static func mileTimeFor (distance:Double,time:Double) ->Double{

return time/(distance/1600)

}

}

let run=RunningWorkout(distance:100, time:20, elevation: 400)

print(run.mileTimeFor())

The whole point of static methods is that their calls are independent of any instance. Either use:

print(RunningWorkout.mileTimeFor(distance: 100, time: 20))

Or make the mile-time calculation dependent on an instance's properties, which implies changing it to a instance-level method (or property here).

struct RunningWorkout {
    var distance, time, elevation: Double

    var mileTime: Double {
        // This calculation doesn't involve elevation?...
        return time / (distance / 1600)
    }
}

let run = RunningWorkout(distance: 100, time: 20, elevation: 400)
print(run.mileTime)

BTW, Development-Compiler is for developing the compiler itself, not developing with the compiler. (The latter would include the former if we self-hosted. But Swift is written in C++, making it the only one of its contemporaries (Kolin, Rust, Go, Scala, etc.) that doesn't self-host.)

1 Like
Terms of Service

Privacy Policy

Cookie Policy