Failable Numeric Conversion Initializers | Swift 3.1

Swift 3.1 implements failable initializers for all numeric types like Int, Int8, Int16, Int32, UInt, UInt8, UInt16, UInt32, Float, Float80, Double. So which either completely successful without loss of information or simply returns nil.

This feature is very useful let’s see an example.

typealias JSONDictionary = [String: AnyObject]
class Employee  {
    let name: String
    let level: Double
    init?(json: JSONDictionary) {
       guard   let name = json["name"] as? String,
           let levelString = json["level"] as? String,
            let levelDouble = Double(levelString),
            let level = Int(exactly: levelDouble)  // 3.1 feature here
            else {
                return nil
        }
        self.name = name
        self.level = level
    }
}

func getEmployees(from data: Data) -> [Employee]?   {
    guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
        let jsonArray = json as? [JSONDictionary]   else {
            return nil
    }

    return jsonArray.flatMap(Employee.init)
}

let jsonString = "[{\"name\":\"John\", \"level\":\"7.2\"}]"
if let data = jsonString.data(using: .utf8) {
    let employees = getEmployees(from: data)
    print(employees ?? "its Nil")
} else {
    print("Data Nil")
}