Reputation: 1247
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 type MyType
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 an Int?
. 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?
Upvotes: 19
Views: 8260
Reputation: 72760
The pattern used in swift is the initializer. So for instance when converting an Int
to UInt
, we have to write:
var i: Int = 10
var u: UInt = UInt(i)
I would stick with that pattern.
As for the subquestion, the documentation states that:
Type casting is a way to check the type of an instance, and/or to treat that instance as if it is a different superclass or subclass from somewhere else in its own class hierarchy.
and
You can also use type casting to check whether a type conforms to a protocol
so no, the as
keyword can`t be used to transform a value of a certain type to another type.
That can be tested in a simple way:
var i: Int = 10
var u: UInt = i as UInt
That generates an error:
'Int' is not convertible to 'UInt'
More about Type Casting
Upvotes: 11