Opposite of __conversion in Swift to assign to a value of a different type

前端 未结 2 962
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 17:04

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

相关标签:
2条回答
  • 2021-01-21 17:37

    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<T> {
        var myString = ""
        var myT : T?
    }
    
    extension String {
        func __conversion<T>() -> MyClass<T> {
            var myInstance = MyClass<T>()
            myInstance.myString = self
            return myInstance
        }
    }
    
    let anInstance: MyClass<Int> = "test"
    

    BTW: I think the Apple approved answer is an init method.

    let anInstance = MyClass(myString: "test")
    
    0 讨论(0)
  • 2021-01-21 18:02

    It turns out that __conversion is a private method and will be removed by the end of the beta so this will definitely not be possible once Swift is released.

    0 讨论(0)
提交回复
热议问题