Nil Exception Handler — Generics in Swift — How to create Generic Handler or Exception Handler in Swift.

Syed Rafay
Swift Closet
Published in
3 min readJan 6, 2021

Definition:

Generic code means to write a code with less dependency on data type or less knowledge of data type. it helps in reusability of code.

Scenerio:

Suppose you are working with network calls, most of the time you got nil exception. The reason may be the key wasn’t there or the key has no value.

Finally your app CRASHED!!!

Now you have two options,

  1. Optional chaining.
  2. Nil-Coalescing Operator.

These both will be acceptable if type is defined. But suppose we don’t know what will be the data type? this happens when server not distinguish between Int and Double.

Now this is a problem!

Here we can use Generics or Generic coding. This link will show you many uses of Generics.

In this article we will be stick with primitive data types.

Lets Code.

  1. Create a swift file by pressing cmd+n with name ExceptionHandler.swift.
  2. Create a class name same as file name.
  3. Create a singleton obj.

//private singleton

private static var _obj:ExceptionHandler? = nil

//singlton object

class var sharedInstance: ExceptionHandler {

get{

if(_obj == nil){

_obj = ExceptionHandler()

}

let lockQueue = DispatchQueue(label: “obj”)

return lockQueue.sync{

return _obj!

}

}

}

4. Create a struct for error description (Optional)

the above part (pt. 4) is optional whether you want to force crash the app use the struct and if not the don’t use this struct. I’ll Show this below

5. Now create a function which will take value as Generic and return a generic.

// Check Any Type of data

func unwrap<T>(_ optional: T?) -> T {

/*Statements*/

if let real = optional {

switch(real) {

case is Float:

if ((real as? Float)! < 1){

return 0 as! T

}else{

return real

}

case is String:

if ((real as? String)?.isEmpty)!{

return “ — “ as! T

}else{

return real

}

case is Int:

if ((real as? Int)! == 0 ){

return 0 as! T

}

else{

return real

}

case is Double:

if ((real as? Double)! < 1 ){

return 0.0 as! T

}

else{

return real

}

case is [String]:

if (((real as? [String])?.count)! < 1 ){

return [“”] as! T

}

else{

return real

}

default :

print(“Default”)

}

} else {

let x = UnwrapError(optional: “”)

throw UnwrapError(optional: x.description)

}

return “” as! T

}

check the last bold part. Its that what we have to change whether you want to allow error or not. If you want to pass default value on nil then change this

let x = UnwrapError(optional: “”)

throw UnwrapError(optional: x.description)

with this,

return “ — “ as! T

Use:

ExceptionHandler.sharedInstance.unwrap(apiData.someValue)

Summary:

Above code snippets shows the how to unwrap optional with generics. Its my approach towards unwrapping.

--

--

Syed Rafay
Swift Closet

IOS Developer - Former Firefox Club Captain - Tech Nerd - Towards Algo Expert - Just Code, Eat and Sleep