Reputation: 18998
I am using Xcode playground to downcast in swift. Typecasting would normally allow me to convert a type to derived type using As operator in swift. But it gives me error while i try to typecast var a as Double,String. Thanks in advance!!
var a = 1
var b = a as Int
var c = a as Double
var d = a as String
Upvotes: 3
Views: 2066
Reputation: 39091
You cannot cast it to each other because they do not relate. You can only cast types that are related like UILabel
and UIView
or [AnyObject]
and [String]
. Casting an Int
to a Double
would be like trying to cast a CGPoint
to a CGSize
So to change for example an Int
to a Double
you have to make a new Double
of that Int
by doing Double(Int)
.
This applies to all numeric types like UInt Int64 Float CGFloat
etc.
Upvotes: 4
Reputation: 2008
Cast as Int works, because a
is Int
You should do it like this:
var c = Double(a)
var d = toString(a) //or String(a)
Upvotes: 0
Reputation: 6195
Try this:
var a = 1
var b = Int(a)
var c = Double(a)
var d = String(a)
Upvotes: 0