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

I use KVC extensively to create a unified interface for the needs of the application. For example, one of my functions receives an object that undergoes several checks based solely on the dictionary of string keys.

So I need a way to check if an object is a collection type key.

I expected to be able to do some protocol checking (e.g. IEnumerable in C # to check if it can be enumerated), but that didn't work:

if let refCollection = kvcEntity.value(forKey: refListLocalKey) as? AnySequence<CKEntity> { ... }

I also tried AnyCollection.

I know that I could iterate over all the basic types of collections by simply typing:

if let a = b as? Set { ...} // (or: if a is Set {...})
if let a = b as? Array { ...}
if let a = b as? Dictionary { ...}

But this does not seem correct in terms of inheritance / polymorphism.

+4
2

Collection , Ahmad F .

. obj-c isKindOfClass, ( Mirror). .

, , , - Array, Dictionary Set ( ):

func isCollection<T>(_ 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
}

:

var set : Set! = Set<String>()
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

- , .

0

:

func isCollection<T>(object: T) -> Bool {
    switch object {
    case _ as Collection:
        return true
    default:
        return false
    }
}

:

// COLLECTION TESTING //

let arrayOfInts = [1, 2, 3, 4, 5]
isCollection(object: arrayOfInts) // true

let setOfStrings:Set<String> = ["a", "b", "c"]
isCollection(object: setOfStrings) // true

// [String : String]
let dictionaryOfStrings = ["1": "one", "2": "two", "3": "three"]
isCollection(object: dictionaryOfStrings) // true


// NON-COLLECTION TESTING //

let int = 101
isCollection(object: int) // false

let string = "string" // false

let date = Date()
isCollection(object: date) // false

, .

+3

Source: https://habr.com/ru/post/1664246/


All Articles