Swift 2: usability issue for Type inference of generic optional types

Number:rdar://21676393 Date Originated:05-Jul-2015 01:57 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode Version 7.0 beta (7A121l)
Classification: Reproducible:
Swift type inference can help a function return the requested result. That is very handy.

However, when optionals are involved, Swift type inference turns FRAGILE. The place of a single question mark can trigger or prevent type inference, without the user being fully aware of her mistake, which yields subtle bugs that are VERY difficult to spot.

Steps to Reproduce:
In the following code, the last lines reveal the fragility of Swift type inference:

protocol Convertible {
    static var value: Self { get }

extension String: Convertible {
    static var value: String { return "good" }

func value() -> Any? { return false }
func value<T: Convertible>() -> T? { return T.value }

// OK: "good"
let int: String? = value()

// OK: "good"
value() as String?

// SURPRISE: nil
value() as? String

This may have well known and good reasons to happen, yet it is a real big nasty surprise. And developers don't like surprises.

Expected Results:
Both `value() as String?` and `value() as? String` return "good".

Actual Results:
`value() as String?` returns "good" and `value() as? String` return nil.

Version 7.0 beta (7A121l)
OSX 10.10.3 (14D136


You may be happy to have some context where this issue turns out to be a real problem.

Please open https://github.com/groue/GRDB.swift/blob/e782b3e88e9ab39bc12d38cb846ac17e3d91f6ba/README.md#row-queries, and scroll down a little to the "WARNING: type inference requires a very careful use of the `as` operator" sentence.




Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!