3

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
1
  • oh sorry i was saying about downcasting...i think what you say is typecast.So how are we going to perform that? Commented Mar 13, 2015 at 9:26

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So, i am really confused on why to use downcasting, if i am not able to cast types to unrelated type? and by the way what do you mean to say that you can only cast to related types?
@rintaro Haha I didnt notice that type, thanks Ill edit it x)
@anishparajuli What I mean is that in Swift (which is really strict on types) you cant just cast something that is not a child of the type you're trying to cast into.
Thats where my example comes in to describe, you can cast UILabel to UIView because UILabel is a subclass of UIView, and you can't cast CGPoint to a CGSize because CGPoint is not subtype of any kind to CGSize or the other way around which makes them not related.
yah now i got the point..if i want to downcast there should be a level of hierarchy between classes.
0

Try this:

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

1 Comment

I posted this, before the question got edited from "typecasting" to "downcasting"
0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.