简体   繁体   English

Swift:实现协议的结构数组

[英]Swift: array of structs implementing protocol

I can't understand why I can't pass an array of structs (which implement a protocol) to a function expecting an array of things that conform to that protocol.我不明白为什么我不能将一个结构数组(实现一个协议)传递给一个需要符合该协议的数组的函数。

I get a compile error at: r.setDataToRender(toRender) --> Cannot convert value of type [Process] to expected argument type [MyType].我在以下位置收到编译错误:r.setDataToRender(toRender) --> 无法将类型 [Process] 的值转换为预期的参数类型 [MyType]。

What I can do is to create an array [MyType] and append each element of toRender and pass that new array instead, but that seems inefficient.我能做的是创建一个数组 [MyType] 并附加 toRender 的每个元素并改为传递该新数组,但这似乎效率低下。

//: Playground - noun: a place where people can play
typealias MyType = protocol<Nameable, Countable>

protocol Nameable {
    func getName() -> String
}

protocol Countable {
    func getCount() -> Int
}

struct Process : MyType {
    let processName: String?
    let count: Int?

    init(name:String, number: Int) {processName = name; count = number}
    func getCount() -> Int {return count!}
    func getName() -> String {return processName!}
}

class Renderer {
    var data  = [MyType]()

    func setDataToRender(d: [MyType]) {
        data = d
    }

    func setOneProcessToRender(d: Process) {
        var temp = [MyType]()
        temp.append(d)
        data = temp
    }
}

var toRender = [Process]()
toRender.append(Process(name: "pro1",number: 3))

let r = Renderer()
r.setOneProcessToRender(Process(name: "pro2",number: 5)) // OK
r.setDataToRender(toRender) // KO

var str = "Hello, Stackoverflow!"

It works if you change it to this:如果您将其更改为以下内容,它会起作用:

var toRender = [MyType]()
toRender.append(Process(name: "pro1",number: 3))

Your function setDataToRender is expecting an array of types MyType .您的函数setDataToRender需要一个MyType类型的数组。 When you instantiated your array you typed it to Process .当你实例化你的数组时,你将它输入到Process Although Process implements MyType it is not identical to MyType .尽管Process实现了MyType它与MyType So you have to create toRender as an array of types MyType to be able to send it to setDataToRender .因此,您必须将toRender创建为MyType类型的数组才能将其发送到setDataToRender

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM