Opt-in Type Conversion Method in Swift

Swift supports opt-in to convert an object to a type via the instance method __conversion(). This method can used through the as operator and is overloadable to support conversion to multiple types:

class X {
  func __conversion() -> String { return "as a string!" }
  func __conversion() -> Double { return 101.2 }
}

println( X() as String )  //Output: as a string!

var d : Double = X()      
println( d )              //Output: 101.2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s