我正在尝试扩展 Array<MutatingCollection>
所以我可以镜像数组数组的内容,但编译器说我不能调用 reverse()
在数组中的元素上,尽管 reverse()
在 MutatingCollection
中定义协议(protocol)。
我想做这样的事情:
var table = [[0,1,2],
[3,4,5],
[6,7,8]]
table.mirror()
//table now [[2,1,0],
// [5,4,3],
// [8,7,6]]
这是我的(不工作的)代码:
extension Array where Element == MutableCollection {
mutating func mirror() {
for index in self.indices {
self[index].reverse()
}
}
}
我已经尝试过 self.map {array in array.reverse()}
以及(我认为做同样的事情,但我没有完全理解 map()
)这两种方式都会导致相同的错误消息:
Member 'reverse' cannot be used on value of type 'MutableCollection'
编辑:我可以直接调用相同的代码,它按预期工作。
也许我正在使用 extension
不正确,或者 Swift Playgrounds 以某种方式阻止了我的访问。
最佳答案
首先,扩展应该这样声明:
extension Array where Element : MutableCollection {
您想检查 Element
遵守协议(protocol) MutableCollection
, 并不是说它是 MutableCollection
但是,我无法调用 reverse
subscript
上的方法因为某些原因。我能做的最好的事情是:
extension Array where Element : MutableCollection {
mutating func mirror() {
for index in self.indices {
self[index] = self[index].reversed() as! Element
}
}
}
虽然强制转换非常丑陋,但我不喜欢这样做,但它会在您需要它工作时起作用。我想我应该测试 Actor 阵容以确定但我看不到任何调用 reversed()
的情况将导致无法转换回 Element
的集合.
编辑:
我想通了这个问题。 reverse()
方法仅在 MutableCollection
上有效当它也是 BidirectionalCollection
时.此代码现在可以正常工作:
extension MutableCollection where
Iterator.Element : MutableCollection &
BidirectionalCollection,
Indices.Iterator.Element == Index {
mutating func mirror() {
for index in self.indices {
self[index].reverse()
}
}
}
现在代码应该适用于所有 MutableCollection
其元素都是 MutableCollection
和 BidirectionalCollection
- 例如 [Array<Int>]
甚至 [ArraySlice<Int>]
您可以查看 reverse()
的完整代码在 Swift 3.1 中:
extension MutableCollection where Self : BidirectionalCollection
关于arrays - Array<MutableCollection> 的 Swift 扩展不允许 reverse(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769532/