One of the things I love about C# is you can define implicit converters for your classes. For instance, I created a VectorGeometryBuilder
class that has methods like MoveForwardByX
, TurnByYDegrees
, LineToPoint
, etc. It then defines an implicit conversion to a Geometry
class. This allows me to use my nifty builder to create my geometry, then just pass the whole object along as-is to any function expecting a Geometry
, even though VectorGeometryBuilder
itself is not a subclass of Geometry.
Instead it exposes a Geometry
object as a property, which the implicit converter grabs and returns.
What I'm wondering is if Swift has something similar.
Consider this made-up scenario...
class FauxInt {
init(_ initialValue: Int) {
value = initialValue
}
var value:Int
}
let fauxInt = FauxInt(14)
// These are the kind of things I'm trying to be able to do...
let realInt:Int = fauxInt
someFuncTakingAnInt(someInt: fauxInt)
Again, the conversion to Int
should be implicit meaning anywhere that's expecting an Int
, I can use or pass a FauxInt
instead.
Is there any way to make the above possible?
Swift doesn't support implicit conversion - the closest equivalent is done through extra constructors. So to convert a Double to an Int:
let i: Int = Int(myDouble)
In your case, you could define an extension to Int to create a new init that takes fauxInit as a parameter:
extension Int {
init(_ myFaux: FauxInt) {
self = myFaux.value
}
}
let fauxInt = FauxInt(14)
let realInt = Int(fauxInt)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With