如何在Swift中继承数组类? [英] How to subclass an array class in Swift?

查看:168
本文介绍了如何在Swift中继承数组类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手。我有一个基类:

I am new in Swift. I have a base class:

class foo{}

我想实现一个foo集合类:

I want to implement a foo collection class:

class foos: Array<foo>{}

但编译器抱怨:


继承非协议,非类型的'Array'

inheritance from a non-protocol, non-class type of 'Array'

我尝试过其他语法(例如 [foo] NSMutableArray< foo> )但是没有一个通过编译器检查。

I have tried other syntax (e.g. [foo] and NSMutableArray<foo>) but none of them passes the compiler check.

这应该很简单,但我整天用Google搜索,无法弄明白。有没有人知道它是否可能,如果是,是否正确的语法?

This should be simple but I have googled all day and could not figure it out. Does anyone know if it is possible and if it is, the correct syntax?

推荐答案

Swift的数组 type是一个结构,在Swift中,基类必须是实际的类(即 class Foo )而不是结构。

Swift's Array type is a structure, and in Swift, base classes must be actual classes (that is, class Foo) and not structures.

不幸的是,你不能通过 Array 的继承来做你想做的事。但是,您可以将数组存储为类中的字段并将方法转发给它,可能实现您要支持的任何协议,等等。

So you cannot do what you are trying to do via inheritance from Array, unfortunately. You could, however, store the array as a field within your class and forward methods to it, possibly implementing any protocols you want to support, et cetera.

这篇关于如何在Swift中继承数组类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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