Can I make a Swift data type infix operator?

139 Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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)
0
On

You can't do this in the way you're asking. It's not possible syntactically to use a operator in a declaration like that.

What you can do is use an enum to distinguish the kinds:

enum NumericInput {
    case integral(Int)
    case fractional(Double)
}

and take that as the type of your variable:

var value: NumericInput

Then you say

value = .integral(someInteger)
2
On

You can just declare the value with type Any.

For example,

var myVar: Any = shouldAssignDouble ? Double(20) : Float(20)

Later when you want to know if the actual type is a Float or Double, you can check it with

myVar is Double //returns true