LC 웃
LC 웃

Reputation: 18998

How to cast numeric types?

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

Answers (3)

Arbitur
Arbitur

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

IxPaka
IxPaka

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

Devran Cosmo Uenal
Devran Cosmo Uenal

Reputation: 6195

Try this:

var a = 1
var b = Int(a)
var c = Double(a)
var d = String(a)

Upvotes: 0

Related Questions