What is currently the best/preferred way to define explicit conversions in Swift? Of the top of my head I can think of two:
Creating custom initializers for the destination type via an extension, like this:
extension String { init(_ myType: MyType) { self = "Some Value" } }
This way, you could just use
String(m)
where m is of typeMyType
to convert m to a string.Defining
toType
-Methods in the source type, like this:class MyType { func toString() -> String { return "Some Value" } }
This is comparable to Swift's
String.toInt()
, which returns anInt?
. But if this was the definitive way to go I would expect there to be protocols for the basic types for this, like an inversion of the already existing*LiteralConvertible
protocols.
Sub-question: None of the two methods allow something like this to compile: let s: MyString = myTypeInstance (as String)
(part in parentheses optional), but if I understand right, the as
operator is only for downcasting within type hierarchies, is that correct?