Skip to content

Instantly share code, notes, and snippets.

@L-A
Created July 20, 2020 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save L-A/1eab955bc12127c97ca2212c44539f4a to your computer and use it in GitHub Desktop.
Save L-A/1eab955bc12127c97ca2212c44539f4a to your computer and use it in GitHub Desktop.
Static struct properties in Swift
struct Vehicle {
// Here are four struct properties: Three are
// required when I initialize an instance, and
// the fourth is computed
var name: String
let consumptionInLper100km: Float
let fuelCapacityInL: Float
var autonomy: Float {
return fuelCapacityInL * (100/consumptionInLper100km);
}
// This is static, and won't be an instance property
static func calculateAutonomy (consumptionInLper100km: Float, fuelCapacityInL: Float) -> Float {
return fuelCapacityInL * (100/consumptionInLper100km);
}
}
// Let's try this out! I create a Yaris instance
let Yaris = Vehicle(
name: "Toyota Yaris",
consumptionInLper100km: 6.72,
fuelCapacityInL: 44
)
print(Yaris.autonomy) // 654.7 kilometers. Cool!
// But if I try to use .calculateAutonomy on my instance:
Yaris.calculateAutonomy(...)
// Nope! Huh.
// Error: Static member 'calculateAutonomy' cannot be
// used on instance of type 'Vehicle'
// This is a property of the vehicle struct itself.
// So I call it straight from the struct/class without
// creating a specific instance.
//It can be handy in a lot of situations.
// Let's say I need nothing else than to
// calculate something's autonomy once:
let ducatiScramblerAutonomy = Vehicle.calculateAutonomy(
consumptionInLper100km: 5.4,
fuelCapacityInL: 13.5
)
print(ducatiScramblerAutonomy) // 250 kilometers!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment