Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift is it possible to create implicit conversions for your class types?

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?

like image 683
Mark A. Donohoe Avatar asked Aug 25 '16 05:08

Mark A. Donohoe


1 Answers

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)
like image 171
Michael Avatar answered Oct 17 '22 06:10

Michael