Safe casting from Int to Int8 in Swift

I get a set of integers through the json api response (which I convert to a dictionary [String: Any]). These integers are guaranteed to be in the range of 10 ... 10 (inclusive). In my model, I would like to save them as Int8.

This is how I convert my json dictionary into a model object, but I wonder if there is a more idiomatic way to ensure that ints in json really fit in Int8?

func move(with dict: JSONDictionary) -> Move? {
    if let rowOffset = dict[JSONKeys.rowOffsetKey] as? Int,
       let colOffset = dict[JSONKeys.colOffsetKey] as? Int {

      if let rowInt8 = Int8(exactly: rowOffset),
         let colInt8 = Int8(exactly: colOffset) {

        return Move(rowOffset: rowInt8, colOffset: colInt8)
      }
      else {
        print("Error: values out of range: (row: \(rowOffset), col: \(colOffset)")
      }
    } else {
      print("Error: Missing key, either: \(JSONKeys.rowOffsetKey) or \(JSONKeys.colOffsetKey)")
    }

    return nil
  }

Note that the following is always executed regardless of the value of the incoming ints:

if let rowOffset = dict[JSONKeys.rowOffsetKey] as? Int8,
   let colOffset = dict[JSONKeys.colOffsetKey] as? Int8 {
...

This is how I convert incoming json to dictionary. The Json in question is deeply nested and contains several different types.

typealias JSONDictionary = [String: Any]
let jsonDict = try JSONSerialization.jsonObject(with: data) as? JSONDictionary
+4
1

Int ( NSNumber) Int8:

Int8 initializer init(_: Int)

Int Int8, Int8(value) .

Int, Int8, :

let i = 300
let j = Int8(i)  // crash!

Int8 init(truncatingIfNeeded: BinaryInteger)

init(truncatingIfNeeded: BinaryInteger):

let i = 300
let j = Int8(truncatingIfNeeded: i)  // j = 44

, , .

:

if (-10...10).contains(i) {
    j = Int8(i)
} else {
    // do something with the error case
}

, , , , Int8.

Int8 init(exactly: Int)

Int8. , nil, Int8. , , , nil ?? , :

// Determine Int8 value, use 0 if value would overflow an Int8
let j = Int8(exactly: i) ?? 0

NSNumber as Int8 Swift 3.0.1

@Hamish @OOPer, NSNumber Int8.

let i: NSNumber = 300
let j = i as Int8  // j = 44

, init(truncatingIfNeeded: BinaryInteger).

, , , , , -10...10, .

+7

Source: https://habr.com/ru/post/1668187/


All Articles