从非协议,非类Type继承 [英] Inheritance from non-protocol, non-class Type

查看:79
本文介绍了从非协议,非类Type继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在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,该占位符继承自(在类),或符合(对于协议)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既不是协议也不是类,所以我假设您真正想要的是不受约束的通用占位符,而是希望将给定类型作为参数传递给函数,该函数将定义.

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
}

这篇关于从非协议,非类Type继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆