在swift

时间:2015-12-14 08:14:23

标签: swift

我有一段如下代码:

protocol SomeProtocol {
}

struct SomeObject: SomeProtocol {
}

struct Test {

    var arr: [[SomeProtocol]]

    mutating func testFunction(objs:[[SomeObject]]) {
        self.arr = objs
    }
}

如您所见,SomeObject确认协议,但编译器向我显示

error " cannot assign value of type '[[SomeObject]]' to type '[[SomeProtocol]]'". 

有人可以告诉我原因吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

由于[[SomeObject]][[SomeProtocol]]的类型不同,请参阅上面的@ TeeJay评论。 如何解决方式如下:

protocol SomeProtocol {
}

struct SomeObject: SomeProtocol {
}

struct Test {

    var arr: [[SomeProtocol]]

    mutating func testFunction(objs:[[SomeObject]]) {
        self.arr = []
        for a in objs {
            var innerArray = [SomeProtocol]()
            for e in a {
                innerArray.append(e)
            }
            self.arr.append(innerArray)
        }
    }
}

或者,正如@MartinR指出的那样,您可以使用map

如果我尝试用

短路内环
    self.arr = []
    for a in objs {
        self.arr.append(a)
    }

我收到错误"无法转换类型'数组< SomeObject>'预期的参数类型[SomeProtocol]",在一个层面上,它是完全正确的 - 它们不相同 - 它是符合协议的元素,而不是集合。除非您明确地执行此操作,否则数组赋值不会深入到协议一致性的最终元素类型。

这并不奇怪 - 你不会期望以下工作:

struct SomeOther1 {
    var a : SomeProtocol
}

struct SomeOther2 {
    var a : SomeObject
}

let x = SomeOther2(a: SomeObject())
let y: SomeOther1 = x // ERROR

虽然这应该(并且确实)有效:

let x = SomeOther2(a: SomeObject())
let y = SomeOther1(a: x.a)

由于Arrays是使用泛型的Struct,我们可以尝试使用泛型:

struct SomeOther<T> {
    var a: T
}

let z = SomeOther<SomeObject>(a: SomeObject()) // OK, of course
let w = SomeOther<SomeProtocol>(a: SomeObject()) // OK, as expected
let v: SomeOther<SomeProtocol> = z // Doesn't work - types are not the same.
相关问题