将UInt16转换为Int16将发生程序崩溃

时间:2015-11-19 14:38:01

标签: swift

当我将UInt16(值超过32767)转换为Int16时,如何避免程序崩溃。

在Object-C中简单安全:

uint16_t a = 32888
int16_t  b = (int16_t)a

但我对Swift没有任何想法。

1 个答案:

答案 0 :(得分:-1)

您可以使用以下功能:

func toInt(unsigned: UInt) -> Int {

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

    return signed
}
相关问题