1

How do i avoid a program crash, when I cast a UInt16(value over 32767) to Int16.

In Object-C is easy and safe:

uint16_t a = 32888
int16_t  b = (int16_t)a

But I don't have any idea in Swift.

CocoaUser
  • 1,361
  • 1
  • 15
  • 30

1 Answers1

-1

You can use the following function:

func toInt(unsigned: UInt) -> Int {

    let signed = (unsigned <= UInt(Int.max)) ?
        Int(unsigned) :
        Int(unsigned - UInt(Int.max) - 1) + Int.min

    return signed
}
Mika
  • 5,807
  • 6
  • 38
  • 83
  • thanks! It works very well. – CocoaUser Nov 19 '15 at 14:58
  • `numericCast(...)` is what you're looking for. It's a set of generic functions that converts from and to different number types. It picks the correct implementation based on the types of its argument and the return type. – stigi May 31 '16 at 01:03