struct NuclearRocket {
var meters: Double
var liters: Double
init(meters: Double, liters: Double) {
self.meters = meters
self.liters = liters
}
// Init for 🇺🇸
init(ft: Double, gallon: Double) {
let convertedMeters = ft / 3.28
let convertedLitter = gallon * 3.78
self.init(meters: convertedMeters, liters: convertedLitter)
}
}
let asdf = NuclearRocket(ft: 1, gallon: 1)
asdf.liters
asdf.meters
thats a.l good for converting feet to metric but how would I switch from metric to feet in the same struct?
Hi @lac_ekim,
Have you looked at using Computed Properties?
Here’s a sample of using computed properties
var inLiters: Double {
return liters
}
var inGallons: Double {
return liters / 3.78
}
and you could set up your object as
let asdf = NuclearRocket(ft:1, gallon:1)
asdf.inLiters
asdf.inGallons
cheers,
Jayant
thank you for showing how, Jayant
Yeah computed properties are great… although they’re computed.
Which is great in the sense that if you EVER need to change liters
, gallons
will automatically be changed.
However it’s also running that math every. single. time.
So if performance is key, consider a separate stored property.
Also, if you want to set gallons in the future as well, computed properties don’t work.
Here’s an example where you get (and set), using stored properties, while still getting the “computed” effect (aka through the didSet
keyword), without infinite loops (using the oldValue
check):
class Object {
var meters: Double {
didSet {
if oldValue != meters {
feet = meters * 3.28
}
}
}
var liters: Double {
didSet {
if oldValue != liters {
gallons = liters / 3.78
}
}
}
var feet: Double {
didSet {
if oldValue != feet {
meters = feet / 3.28
}
}
}
var gallons: Double {
didSet {
if oldValue != gallons {
liters = gallons * 3.78
}
}
}
init(meters: Double, liters: Double) {
self.meters = meters
self.liters = liters
feet = meters / 3.28
gallons = liters / 3.78
}
init(gallons: Double, feet: Double) {
self.feet = feet
self.gallons = gallons
meters = feet / 3.28
liters = gallons * 3.78
}
}
let test = Object(gallons: 1, feet: 1)
test.gallons = 4
print(test.feet)
print(test.gallons)
print(test.meters)
print(test.liters)
test.liters = 4
print(test.feet)
print(test.gallons)
print(test.meters)
print(test.liters)
this prints
1.0
4.0
0.304878048780488
15.12
1.0
1.05820105820106
0.304878048780488
4.0
WoW thank you for sharing! You guys are the best, TY.
@jayantvarma @personalcompass