Swift Protocol to accept different data types

As the developer of private CocoaPods in our team, it’s nice to modify the frameworks to make team member’s life easier.

In Google Analytics, the sendEvent() method requires NSNumber? as the value passed in.

However, it would be inconvenient if we have to convert our numbers into NSNumber every time we call the sendEvent method:

let number = "88.8"   // The value we wanted to pass to sendEvent
if let value = Double(number) as NSNumber? { 
GAHelper.sendEvent(screen: "SubView", category: "Sports", action: "Purchase", label: "quantity", value: value)

So my goal is to let sendEvent() accept String, Int, Float, Double, nil instead of NSNumber 。My workaround is to use protocol and accept these different data types; Use extensions to get the NSNumber? computed property.

String is troublesome because it cannot directly convert to NSNumber?. We’ll have to convert String into Double? , then to NSNumber? .

The output of String must include a ? as optional value since it may not successfully convert if we give it a non-sense string like 23g45 . I’ll give it a nil as default value.

Next, change the sendEvent() method to accept that ptotocol:

Well done! It works quite nice and my team members wouldn’t have to do conversions every time they use sendEvent() method.