Simplified cast() method for Swift objects

Originator:rainerbrockerhoff
Number:rdar://17827598 Date Originated:28/7/2014
Status:Open Resolved:
Product:Xcode Product Version:6.0
Classification: Reproducible:
 
Summary:
Though the temporary/undocumented implicit __conversion() method will be removed, useful applications for it have been published. (See http://nomothetis.svbtle.com/clean-regular-expressions-using-conversions for an example.)

A possible solution would be to avoid the "implicit" part entirely by allowing such a method to be invoked only by the type-casting operators 'as' and 'as?'.

I propose a 'special member', like 'init' or 'subscript'. It might be 'as' or 'cast'. An example:
public class HoldsAValue<T> {
     var val:T
     init(_ v:T) {
          val = T
     }
     cast()->T {
          return val
     }
}
...
let something = SomeObject()
let h = HoldsAValue(something)     // h will be an instance of HoldsAValue
...
let x = h as SomeObject     // that would invoke SomeObject.cast()

While a similar effect could be produced for concrete types by writing an extension on SomeObject, this doesn't seem to be possible in the generics case. One use case for this is, for instance, my Future class in https://github.com/rbrockerhoff/SwiftChecker/blob/master/SwiftChecker/Future.swift.

The cast() special member would, therefore, be sort of symmetrical to init(), passing another type out instead of in.

An additional advantage would be that all the likely conversions could now be contained inside the type definition, and without proliferating names for such conversions. For instance, toInt(), toString(), toUTF16CodeUnit(), toRaw(), etc., could all be written using the 'as' operator.

In addition, if the cast() method is defined as returning an Optional, the 'as?' operator will be automatically supported.

Comments


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!