【问题标题】:Determine Collection type in Swift确定 Swift 中的集合类型
【发布时间】:2017-12-06 14:25:36
【问题描述】:

我有一个函数,它的标题看起来像这样

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

如您所见,它以 Collection 作为参数,表示它可以是 Array、Set 或 Dictionary,如何在运行时检查此函数中传递的参数类型?

【问题讨论】:

  • 你为什么要这个?
  • @Hamish 我想通过调用一个通用函数来对我的集合类型进行排序,该函数将 Collection 作为输入作为返回排序数组
  • 这并不能解释为什么你要“在运行时检查在这个函数中传递的参数类型”——泛型的重点是你不应该有进行这种运行时类型检查。
  • @Hamish 而不是为每个集合类型编写不同类型的函数我想编写一个通用函数,该函数适用于任何类型的集合,即使是海关的
  • @Zubair, that will work on any type of collection even for customs one's — 如果您手动检查内部集合的类型,这将如何工作?

标签: swift generics collections


【解决方案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 []
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2018-09-26
    • 1970-01-01
    • 2010-12-23
    • 2015-01-25
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多