简体   繁体   English

将值强制转换为未知元素类型的数组

[英]Cast value to array of unknown `Element` type

Assuming a function that operates on any Array : 假设一个函数可以在任何Array上运行:

func g<T>(array: [T]) -> Void {
  // ...
}

...and a function that receives a value of type Any : ...以及接收类型为Any的值的函数:

func f(x: Any) -> Void {
  if x is Array {
    // g(?)
  }
}

How can I get a properly typed version of x that I can pass to g ? 如何获得可以传递给gx的正确类型的版本?

Note that g doesn't rely (explicitly) on the type T . 注意, g不(明确地)依赖类型T All it needs is the ability to iterate over the elements, which can be treated as values of type Any . 它需要的只是对元素进行迭代的能力,可以将其视为Any类型的值。 Any solution that rewrites g to remove the type parameter is therefore also acceptable. 因此,重写g删除type参数的任何解决方案也是可以接受的。

Edit : to make things harder, I'd like this to work on Linux, where Swift arrays aren't NSArray s until you've called .bridge() on them. 编辑 :为了使事情变得更困难,我希望它可以在Linux上工作,在Swift数组中,除非您对它们调用.bridge().bridge()它们不是NSArray

Warning Please note that the below results are based on my experiments on Mirror and work in Swift 2.1.1 (Xcode 7.1.1). 警告请注意,以下结果基于我在Mirror上的实验,并在Swift 2.1.1(Xcode 7.1.1)中工作。 It might be that future Swift versions will change the Mirror behaviour. 未来的Swift版本可能会改变Mirror行为。

If finding out dynamically if the value is an array of any type, you could use Swift's reflection support, via the Mirror struct: 如果可以动态发现该值是否为任何类型的数组,则可以通过Mirror结构使用Swift的反射支持:

func processArray(array: Any) -> Bool {
    let mirror = Mirror(reflecting: array)
    guard mirror.displayStyle == .Collection else {
        return false
    }

    print("array has \(mirror.children.count) elements")

    return true
}

func f(x: Any) {
    if processArray(x) {
        // i just found an array
    }
}

f([1, 2, 3, "4"]) // prints "array has 4 elements"

if you want to keep the generic, you could do this instead: 如果要保留通用名称,则可以执行以下操作:

func g<T>(array: [T]) -> Void {

}

func f(x: Any) -> Void {
    if let array = x as? [Any] {
        g(array)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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