Swift provides a special method called __conversion
that allows you to implicitly convert your type to another type. I would like to be able to define a method that
Have you tried adding an extension to String?
extension String {
func __conversion() -> MyClass {
var myInstance = MyClass()
myInstance.myString = self
return myInstance
}
}
It worked in an iOS playground in Xcode 6 Beta 4.
let anInstance: MyClass = "test"
To deal with generics:
class MyClass {
var myString = ""
var myT : T?
}
extension String {
func __conversion() -> MyClass {
var myInstance = MyClass()
myInstance.myString = self
return myInstance
}
}
let anInstance: MyClass = "test"
BTW: I think the Apple approved answer is an init method.
let anInstance = MyClass(myString: "test")