协议类型无法实例化 [英] Protocol type cannot be instantiated

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

问题描述

考虑以下代码:

protocol Color {
    var color: UIColor { get }
}

struct Ball : Color {
    var color: UIColor
}

let ball = Ball(color: .white)
print(ball)

这有效,并且导致:

Ball(color: UIExtendedGrayColorSpace 1 1)

现在,我想在协议中创建一个函数,给定颜色数组,返回具有该颜色的项目(球或符合Color的任何其他类型)数组:

Now, I would like to make a function in the protocol, that given an array of colors, returns an array of items (balls, or any other type that conforms to Color) with that color:

extension Color {
    func multipleColors(colors: [UIColor]) -> [Color] {
       var coloredItems = [Color]()
       for item in colors {
        // What do I put here ???
       }

       return coloredItems
    }
}

然后:

let coloredBalls = ball.multipleColors(colors: [.red, .green, .blue])

我无法弄清楚放在括号内的内容.例如(如果没有尝试),如果我尝试:

I cannot figure out what to put inside the brackets. For instance (no pun), if I try:

coloredItems.append(Color(color: item))

错误是:

'Color' cannot be constructed because it has no accessible initializers

然后我将init方法添加到协议中,并且错误更改为:

I then added an init method to the protocol, and the error changed to:

protocol type 'Color' cannot be instantiated

我该如何解决?

推荐答案

您正在尝试创建协议Color(color: item)的实例,这是不可能的.

You are trying to create an instance of a protocol Color(color: item), which is not possible.

在下面找到一种可能的通用解决方案.到目前为止,我找不到非静态(好的)解决方案.

Find one possible generic solution below. I could not find a non-static (nice) solution so far.

protocol Color {
    var color: UIColor {get set}
    init(color: UIColor)
}

struct Ball : Color {
    var color: UIColor
}

extension Color {
    static func item<T:Color>(_ item: T, inColors colors: [UIColor]) -> [T] {
        var coloredItems = [T]()
        for color in colors {
            let newColoredItem = T.init(color: color)
            coloredItems.append(newColoredItem)
        }

        return coloredItems
    }
}

let ball = Ball(color: .white)
let coloredBalls = type(of:ball).item(ball, inColors: [.red, .green, .blue])

print(coloredBalls)

打印:

[Ball(color: UIExtendedSRGBColorSpace 1 0 0 1), Ball(color: UIExtendedSRGBColorSpace 0 1 0 1), Ball(color: UIExtendedSRGBColorSpace 0 0 1 1)]

这篇关于协议类型无法实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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