[swift-users] Implicitly type conversion ?

Tim Vermeulen tvermeulen at me.com
Fri Aug 19 11:00:51 CDT 2016


Any idea why Swift supports implicit casting to AnyHashable, but not to, say, AnySequence?

> > On Aug 18, 2016, at 9:54 AM, Adel Zhang via swift-users<swift-users at swift.org>wrote:
> > 
> > Any other situation when implicit type casting works?
> I don't know if there's a comprehensive list anywhere. Here are the ones I can think of:
> 
> 1. A subtype can be used where a supertype is expected; for instance, you can pass an `Int` to a parameter typed `Any` without a cast. The same is true of superclasses: `NSString` can be used where `NSObject` is expected. Obvious, but worth mentioning.
> 
> 2. Swift 3's `AnyHashable` isn't *really* a supertype of `Hashable` types, but it's sort of treated as one.
> 
> 3. The built-in `Array`, `Dictionary`, `Set`, and `Optional` types can be implicitly converted to the same data structure, but with supertypes of its generic parameters. For instance, an `Array<Int>` can be passed to a parameter of type `Array<Any>`. This is not a general feature of generics—it's special-cased for these types.
> 
> 4. As you noticed, a type can be implicitly made more `Optional`; that is, `Int` converts to `Optional<Int>`, `Optional<Optional<Int>>`, and so on.
> 
> 5. In Swift 2, importing Foundation activates many implicit conversions between Foundation and Standard Library types, including conversions to AnyObject. Many (perhaps all?) are gone in Swift 3. (However, Foundation still has plenty of magical `as` casts.)
> 
> Hope this helps,
> --
> Brent Royal-Gordon
> Architechies
> 
> 
> 
> 


More information about the swift-users mailing list