I\'m extensively using KVC to build unified interface for the needs of an app. For instance, one of my functions gets an object, which undergoes several checks based solely
Collection can no longer be used for type-checking, hence Ahmad F's solution would no longer compile.
I did some investigation. Some people advice to bridge to obj-c collections and use isKindOfClass, others try to employ reflection (by using Mirror). Neither is satisfactory.
There's a pretty straight-forward, a bit rough yet efficient way to accomplish the task via splitting object type if our concern is Array, Dictionary or Set (list can be updated):
func isCollection(_ object: T) -> Bool {
let collectionsTypes = ["Set", "Array", "Dictionary"]
let typeString = String(describing: type(of: object))
for type in collectionsTypes {
if typeString.contains(type) { return true }
}
return false
}
Usage:
var set : Set! = Set()
var dictionary : [String:String]! = ["key" : "value"]
var array = ["a", "b"]
var int = 3
isCollection(int) // false
isCollection(set) // true
isCollection(array) // true
isCollection(dictionary) // true
Hard-code is the drawback but it does the job.