【问题标题】:Pass type to generic function and compare将类型传递给泛型函数并进行比较
【发布时间】:2014-12-31 11:09:14
【问题描述】:

考虑这个简单的例子

func contains<T>(type t: T.Type) -> Bool {
    for i in 0..<list.count {
        if list[i] is t { // compiler says: 't' is not a type
            return true
        }
    }
    return false
}

编译器响应

't' is not a type

由于我无法声明静态类型并使用is MyStaticType 进行检查,我如何使用泛型在 Swift 中完成此操作?

【问题讨论】:

    标签: swift


    【解决方案1】:

    你应该检查它是否是T

    if list[i] is T {
        ...
    }
    

    【讨论】:

      【解决方案2】:

      那是因为t 确实不是类型。它是Metatype 类型的实例:

      let x = NSString.self
      // compiler error because the following is 
      // always true but you get the idea...
      x is NSString.Type
      

      您只想检查T,它是实际类型,但可以使用T.Type 来确定@​​987654326@ 是什么:

      // genericised a bit, to make list an argument
      func contains
        <S: SequenceType, T>
        (list: S, type t: T.Type) -> Bool {
          for element in list {
              if element is T {
                  return true
              }
          }
          return false
      }
      
      let a = ["a","b","c"]
      contains(a, type: String.self)    // true
      contains(a, type: NSString.self)  // true
      contains(a, type: Int.self)       // false
      contains(a, type: NSNumber.self)  // false
      
      let b: [Any] = [1, 2 as NSNumber, "c" as NSString]
      contains(b, type: String.self)    // true
      contains(b, type: NSString.self)  // true
      contains(b, type: Int.self)       // true
      contains(b, type: NSNumber.self)  // true
      

      请记住,T 在编译时仍然是静态确定的,而不是动态确定的。所以:

      let c: NSObject = 1 as NSNumber
      contains(a, type: c.dynamicType)
      

      返回true not false,因为它正在检查NSObject(因为c.dynamicType的结果类型是NSObject.Type而不是NSNumber.Type)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-31
        相关资源
        最近更新 更多