简体   繁体   中英

Determine Collection type in Swift

I've a function whose header looks like this

func doSomethingOnCollection<T:Collection>(_ array: T) -> [T]

as you can see it takes Collection as a parameter, meaning it can be Array, Set or Dictionary, how can I check type of parameter passed in this function at runtime ?

Swift documentation says:

Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.

func doSomethingOnCollection<T: Collection>(_ param: T) -> [T] {
    if param is Array<Any> {
        print("Array")
    }
    // We can't say 'Set<Any>', since type of set should conform
    // protocol 'Hashable'
    else if param is Set<Int> {
        print("Set")
    }
    // For the same reason above, we can't say 'Dictionary<Any, Any>'
    else if param is Dictionary<Int, Any> {
        print("Dictionary")
    }
    return []
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM