user3610227
user3610227

Reputation:

Any type in swift and conversion to Int

I've a placeholder object, basically in context of my application, the function carries a playload from one place to the other. I've assigned it the type Any but it's ending up in error

'Any' is not convertible to Int

I'm using Any instead of AnyObject as it can carry non object as well like tuples or closures. Any advise in the following case?

var n: Any = 4

n = n * 4

Upvotes: 1

Views: 1821

Answers (3)

GoZoner
GoZoner

Reputation: 70155

In a strongly typed language it is important to get your types right as early as possible. Otherwise you'll end up fighting the type system at every turn.

In your case, the placeholder, as you've described, needs to be Any because it is carrying arbitrary data - but n is an Int and should be declared as such.

Your code should have this feel:

func processPlaceholder (placeHolder: Any) {
  if let n = placeHolder as? Int {
    n = n * 4
    // ...
  }
  else if let s = placeHolder as? String {
    s = s + "Four"
    // ....
  }
  // ...
}

Upvotes: 1

matt
matt

Reputation: 535201

The other answers are perfectly right. This is just to clarify.

Yes, it's an Int under the hood. But not as far as the compiler is concerned! You have typed this thing as an Any and that's all the compiler knows. And you cannot do arithmetic operations with an Any.

If you insist on storing this thing in an Any, then you must cast down to an Int in order to use it as if it were an Int. Now the compiler will let you treat it as an Int. And it will work, too, as long as it really is an Int. (If you lie and it is not an Int, you'll crash when the program runs.)

Upvotes: 0

Connor
Connor

Reputation: 64644

If you know n is an Int you can cast it as such.

var n: Any = 4
n = n as Int * 4

n will still be of type Any, so if you want to do multiple operations you will have to cast it each time.

Upvotes: 0

Related Questions