1

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?

TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • The `as?` is related to whether one object is explicitly bridgeable to a type different than its own (`oneObject as? anotherType`). You cannot overload this behaviour, and you cannot implement such bridgings using official features in current Swift. If `Growable` was a reference type (e.g. a `Class`), however, you could use undocumented privcate features; conformance to `_ObjectiveCBridgeable` to allow explicit bridging from one typ to another (and in Swift < 3, implicit bridging the other way around). See [the following answer](http://stackoverflow.com/a/38490644/4573247) for such an example. – dfrib Aug 24 '16 at 13:31
  • Interesting problem. Have you tried to overload 'as' like you did with '>>'? – jboi Aug 24 '16 at 13:37
  • You said you wanted to make the code more Swifty, but that's not how casting are done in Swift. Its language designers have intended very clearly that type casting should be done through the init syntax: `let aDouble = Double(anInt)`. I think C3 supports what you asked, but not Swift. (Not saying one is better than the other, just what Apple decided) – Code Different Aug 28 '16 at 17:17

0 Answers0