Sunday, February 1, 2015

Dynamic Casting in Swift

Samuel E. Giddins:

We can even define some syntactic sugar on top of this type verification:

func id<U>(object: AnyObject) -> U? {
  if let typed = object as? U {
    return typed
  }
  return nil
}

[…]

OK, that last example might not look like a huge improvement, but coupled with Swift’s powerful type inference, you can 'magically’ type objects at runtime with a single function call.

You have to call the id() function, but depending on the context Swift may be able to infer the types.

Comments RSS · Twitter

Leave a Comment