Kolja
Kolja

Reputation: 1247

Defining explicit conversion for custom types in Swift

What is currently the best/preferred way to define explicit conversions in Swift? Of the top of my head I can think of two:

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

Answers (1)

Antonio
Antonio

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

Related Questions