In Swift, can I create implicit conversions for your class types?

One of the things I like about C # is defining implicit converters for your classes. For example, I created a class VectorGeometryBuilderthat has methods such as MoveForwardByX, TurnByYDegrees, LineToPoint, etc. Then it defines an implicit conversion to a class Geometry. This allows me to use my graceful builder to create my geometry, and then simply pass the entire n-caboodle kit to any function that expects Geometry, even if VectorGeometryBuilderit is not a subclass by itself. Geometry.Instead, it exposes a Geometryobject as a property that the implicit converter grabs and returns .

What interests me is if Swift has something like that.

View this creation script ...

class FauxInt
{
    init(_ initialValue:Int)
    {
        value = initialValue
    }
    var value:Int
}

let fauxInt = FauxInt(14)

, ...

let realInt:Int = fauxInt

someFuncTakingAnInt(someInt:fauxInt)

, Int , Int, a FauxInt.

?

+4
1

Swift - . , Double Int:

let i: Int = Int(myDouble)

Int init, fauxInit :

extension Int {
    init(_ myFaux: FauxInt) {
        self = myFaux.value
    }
}

let fauxInt = FauxInt(14)
let realInt = Int(fauxInt)
+5

Source: https://habr.com/ru/post/1652408/


All Articles