Caleb Kleveter
Caleb Kleveter

Reputation: 11494

Casting to a type held in a variable

I am attempting to cast a variable to a different type that is held in a variable or is the return type of a function. Here is the idea:

let i = 1 as type(of: 3.14)

But when I do this, I get a couple of errors:

And a warning:

How to I cast a value to a type that is held in a variable?

Upvotes: 9

Views: 1519

Answers (2)

GetSwifty
GetSwifty

Reputation: 7756

Swift (currently) requires the Type assignment at compile time. You can do some things like this, but you will need to write a converter for each type combination you want to use, e.g:

func convertType(from item: Int) -> Float {
    return Float(item)
}

var item: Float = convertType(from: 1)

I would caution going down this road and try and get used to Swift's way of doing things. If you absolutely need it you should be able to use some generic functions with a protocol like FloatConvertable to handle this more simply.

Upvotes: 4

Connor Neville
Connor Neville

Reputation: 7361

The Swift grammar doesn't allow for these types of expressions. The expression after as must be the name of a type, ie. 1 as Double (though, as vadian points out, you can't cast numeric types to each other, so a better example would be mySubClassObject as MySuperClass). Swift is a strongly typed language, which means it needs to know the types of all variables at compile time.

Upvotes: 1

Related Questions