[swift-users] Implicitly type conversion ?

Jordan Rose jordan_rose at apple.com
Fri Aug 19 13:28:49 CDT 2016


It's mainly to support heterogeneous dictionary literals. There's not usually a need to upcast to AnySequence regularly, since most things that take sequences should be using generics, but heterogeneity and generics don't play well together.

Jordan


> On Aug 19, 2016, at 9:00, Tim Vermeulen via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
> 
> 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 <mailto: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
>> 
>> 
>> 
>> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org <mailto:swift-users at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160819/8003ad77/attachment.html>


More information about the swift-users mailing list