Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 381
Anish Parajuli 웃 Avatar asked Jan 25 '26 04:01

Anish Parajuli 웃


1 Answers

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.

like image 144
Arbitur Avatar answered Jan 27 '26 18:01

Arbitur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!