热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

是否可以创建一个struct实例数组?-Isitpossibletocreateanarrayofstructinstances?

Iamtryingtocreateanarrayofstructinstanceslikethis:我试图创建一个这样的struct实例数组:letinstallers:

I am trying to create an array of struct instances like this:

我试图创建一个这样的struct实例数组:

let installers: [AnyObject] = [Homebrew(), Ls()]

But I get this error:

但我得到这个错误:

value of type 'Homebrew' does not conform to expected element type 'AnyObject'

When I give the array no type, I get an ambiguous type error and that it needs more context.

当我给数组没有类型时,我得到一个模糊的类型错误,它需要更多的上下文。

Is it possible to accomplish what I am trying to do?

是否有可能完成我想要做的事情?

I Googled all over, but I can't find anything.

我用Google搜索,但我找不到任何东西。

3 个解决方案

#1


5  

For structs use Any instead of AnyObject.

对于结构使用Any而不是AnyObject。

let installers: [Any] = [Homebrew(), Ls()]

#2


2  

As Rob proposed above, I have created a simple protocol type InstallerType to help you with this. Instead of having it to conform to Any or AnyObject protocols, conforming it to some specific type would categorise your objects in better way.

正如Rob上面提到的,我创建了一个简单的协议类型InstallerType来帮助你解决这个问题。它不是使其符合Any或AnyObject协议,而是将其与某些特定类型相符合,以更好的方式对您的对象进行分类。

extension Homebrew: InstallerType { }
extension Ls: InstallerType { }

let installers: [InstallerType] = [Homebrew(), Ls()]

#3


2  

Following @RobNapier 's suggestion from his comment, I built a protocol. Because both structs use the id and command constants, I came up with this:

根据@RobNapier的评论建议,我建立了一个协议。因为两个结构都使用id和命令常量,所以我想出了这个:

protocol CKInstall {
  var id: String {get}
  var command: [String] {get}
}

Problem solved!

问题解决了!


推荐阅读
author-avatar
Turkey小白
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有