确定Swift中的Collection类型

时间:2017-12-06 14:25:36

标签: swift generics collections

我的标题看起来像这样的函数

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

你可以看到它将Collection作为参数,这意味着它可以是Array,Set或Dictionary,如何在运行时检查此函数中传递的参数类型?

1 个答案:

答案 0 :(得分:1)

Swift documentation说:

  

使用类型检查运算符(is)检查实例是否属于   某些子类型。如果是,则类型检查运算符返回true   instance属于该子类类型,如果不是,则为false。

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 []
}