Search code examples
swiftswift3user-defined-data-types

Can I make a Swift data type infix operator?


So, I want to make an operator ('or') which will allow me to declare a variable like this:

var someNum: Int or Double

This bring an example. I want to actually use it on some custom made data types. But is it possible to make an operator for variable declarations that will allow for said variable to be one of two types depending on what its being assigned? I know what data types are possible of being entered, but unfortunately I would currently either assign it a type of 'Any' with a bunch of failsafe code implemented or change the original data types created. So I was just wondering if this is possible or might even exist.

I used this article as a reference, but from what I read I'm not sure if I can or how I would implement it for my needs. Custom Operators in Swift

Thanks for any and all the help in advance.


Solution

  • You could do this with generics:

    struct MyStruct<T>
    {
        var someNum: T
    }
    

    You can then explicitly state the dataType you wish to use by specifying the type on creation: let a = MyStruct<Int>(someNum: 4).

    One thing Swift does that makes this all absolutely beautiful is derive the data type from the constructor, so you can also just do this:

    let intStruct   = MyStruct(someNum: 4)
    let floatStruct = MyStruct(someNum: 5.0)