How do I check if an object is a collection? (Swift)

前端 未结 3 1123
走了就别回头了
走了就别回头了 2021-01-05 11:51

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

3条回答
  •  悲哀的现实
    2021-01-05 12:45

    You could create another protocol

    protocol CountableCollection {
        var count: Int { get }
    }
    
    extension Array: CountableCollection where Element: Any {
    }
    
    extension Dictionary: CountableCollection where Key == String, Value == Any {
    }
    

    Add all the methods that you need from Collection to the new protocol that has been created (I have added just count getter for demonstration).


    After this you could simply do

    if someVar is CountableCollection {
        print(someVar.count)
    }
    

    someVar would be true if it is an Array or Dictionary. You can also make it conform to Set if required.

提交回复
热议问题