David Kristensen
David Kristensen

Reputation: 31

Swift: Errors when using different integer sizes

I've been trying out Swift, since it's obviously the direction that Apple wants us to go in. However, I've been really annoyed with the fact that you can't seem to add integers of different sizes:

    var a: Int64 = 1500
    var b: Int32 = 12349

    var c = a + b
    if a < b { ... }

The yielded error is "Could not find an overload for '+' that accepts the supplied argument' — obviously since they are object types. None of the class methods seem to be of any help in up/down-converting integers.

Same situation applies with any of the type aliases, obviously, (CInt + CLong).

I can see a lot of real-world situations where it is immensely practical to be able to do integer arithmetic let alone comparisons or bitwise operations on two disparately-sized integers.

How to solve this? Explicit casting with the as operator doesn't seem to work. The Swift language book isn't much help either as it doesn't really discuss this scenario.

Upvotes: 1

Views: 9165

Answers (2)

Gaurav Gilani
Gaurav Gilani

Reputation: 1584

let a: Int64 = 1500
let b: Int32 = 12349
let c = a + Int64(b)
println("The value of c is \(c)")

Upvotes: 7

nschum
nschum

Reputation: 15422

The Swift language book does discuss this scenario in the chapter “Numeric Type Conversion”:

let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)

Because both sides of the addition are now of type UInt16, the addition is allowed. The output constant (twoThousandAndOne) is inferred to be of type UInt16, because it is the sum of two UInt16 values.

Upvotes: 7

Related Questions