Reputation: 11494
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:
type
and (of: 3.14)
)And a warning:
(of: Double)
is unusedHow to I cast a value to a type that is held in a variable?
Upvotes: 9
Views: 1519
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
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