I have a type that I would like to handle casting in a custom way. Essentially, I'd like to overload the as
operator, but I don't know if this is possible.
Here's what I have:
let item = MyObject()
let newItem = item as? Growable
However, I'd like to make the casting nil
if one of the property values doesn't meet a condition. I know I can do it like this:
extension MyObject {
public func asGrowable() -> Growable? {
switch left.type {
case .abc: return left as Growable?
default: return nil
}
}
}
let newItem = item.asGrowable() //Success
item.type = .abc
let newItem2 = item.asGrowable() //nil
However, I was hoping for a more Swifty way using infix
operators so I can do something like this:
func >> (left: MyObject, right: Growable.Type) -> Growable? {
switch left.type {
case .abc: return left as Growable?
default: return nil
}
}
let newItem = item >> Growable //Success
item.type = .abc
let newItem2 = item >> Growable //nil
I can't get the syntax right for the infix
though. Growable.Type
is not correctly allowing me to pass in a protocol type. Is this possible or is there a better way to do this?