在数组中查找特定类型的项目 [英] Find item of specific type in array
问题描述
我想要在Array上扩展,您可以在其中找到某种类型的项目.
I want an extension on a Array where you can find an item that is of some type.
我尝试过这样:
func findItem<U: Type>(itemToFind: U) -> AnyObject? {
for item in self {
if let obj = item as? itemToFind {
return obj
}
}
return nil
}
所以我检查它是否是相同类型,然后我想返回obj.
So I check if it is the same type and then I want to return the obj.
我得到的错误是:
从非协议,非类类型"继承.
Inheritance from non-protocol, non-class 'Type'.
我该如何解决这个问题,以便可以传递给函数 ViewController.self
,并在找不到时返回nil或数组中的viewcontroller呢?
How can I fix this that I can pass to the function ViewController.self
and that I get back nil if not found or the viewcontroller that is in the array?
推荐答案
在这种情况下,语法< U:Type>
表示您要声明一个新的通用占位符 U 函数签名中的code>,它是继承自(对于类而言)还是符合(对于协议而言)
Type
.
The syntax <U: Type>
in this context means you're declaring a new generic placeholder U
in your function signature, which inherits from (in the case of classes), or conforms to (in the case of protocols) Type
.
由于 Type
既不是协议也不是类,所以我假设您真正想要的是不受约束的通用占位符,而是希望将给定类型作为函数的参数传递,该函数将定义 U
的类型.
As Type
is neither a protocol nor class, I assume what you really want is an unconstrained generic placeholder, and instead want to pass in a given type as an argument to the function, which will define the type of U
.
In this case, you'll want to use the metatype U.Type
as the function input type (as well as U?
for the function return type – as the return type will be the optional type of whatever type you pass into the function). For example:
extension Array {
func firstElement<U>(ofType _: U.Type) -> U? {
for element in self {
if let element = element as? U {
return element
}
}
return nil
}
}
let array : [Any] = [2, "bar", 3, "foo"]
print(array.firstElement(ofType: String.self)) // Optional("bar")
As a side note, this could be simplified slightly by using pattern matching in the for
loop:
func firstElement<U>(ofType _: U.Type) -> U? {
for case let element as U in self {
return element
}
return nil
}
这篇关于在数组中查找特定类型的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!