2016-02-18 52 views
3

我正在將一些舊的C代碼導入swift項目,並將其移植到純swift代碼中。Swift:如何禁用函數的整數溢出/下溢陷阱

一些它「加密」,其中確實像

let a = UInt8(x) // e.g. 30 
let b = a - 237 

在C這只是溢和環繞,這是罰款,這種特定的功能。

在swift中,這觸發了一個fatalError,並用EXC_BAD_INSTRUCTION終止了我的程序,因爲默認情況下swift被設計爲捕獲整數溢出/下溢。

我知道我可以通過編譯-Ofast在整個項目級別關閉此檢查,但我真的很想關閉溢出檢查這一行代碼(或者只是特定的功能本身)。

注:我特別想保留C函數的行爲,而不僅僅是促進東西來的Int32或Int64的

這特定的詞,似乎真的很難谷歌。


更新:答案是Overflow operators,這是

  • &-減法
  • &+加法
  • &*爲乘法

我無法找到他們在我以前的搜索。哎呀

+4

使用溢出運算符,例如'&-' – Cosyn

回答

4

您可以使用int,UINT8的addWithOverflow或subtractWithOverflow類方法等類型

例如let b = UInt8.subtractWithOverflow(a, 237)

+1

我最終使用了溢出運算符'&-',但是我無法投票評論爲接受的答案 –

0
從溢流運營商

除了(如& +,& *等),你可以使用報告溢出的方法(適用於整數)的瞭解運算是否導致溢出或沒有像這樣的例子:

let int1 : Int8 = Int8.max //127 
    let int2: Int8 = 50 

//this method provides a boolean flag 
    let (sum1,didOverflow):(Int8,Bool) = int1.addingReportingOverflow(int2) 

    print("sum is \(sum1) and isOverflowing = \(didOverflow)") 
//sum is -79 and isOverflowing is true 

    let sum = int1 &+ int2 //wont crash for overflows 
    let unsafeSum = int1.unsafeAdding(int2) //crashes whenever overflow