Hon*_*ney 7 arrays struct immutability swift
struct Queue<T>{
private var elements : [T] = []
public mutating func enqueue(_ element: T){
elements.append(element)
}
public mutating func dequeue() -> T?{
return elements.popFirst() // ERROR!
}
public mutating func dequeue2() -> T?{
return elements.removeFirst()
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误popFirst是:
不能对不可变值使用变异成员:“自身”不可变
双方popFirst并removeFirst标记为mutating两者的回报和T?。那为什么不起作用呢?
编辑: 正如其他人评论,这似乎是某种错误。已经在这里的论坛中进行了讨论。
编辑:在Xcode 9.4.1(Swift 4.1.2)中仍然会发生
该错误在 Swift 4.2 中得到改进:
error: ios.playground:4:25: error: '[T]' requires the types '[T]' and 'ArraySlice<T>' be equivalent to use 'popFirst'
return elements.popFirst() // ERROR!
^
Run Code Online (Sandbox Code Playgroud)
您收到错误,因为popFirst未为所有Collections定义。只有当Collection是它自己的SubSequence类型时才定义它。这是实现:
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popFirst() -> Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
Run Code Online (Sandbox Code Playgroud)
我假设扩展需要SubSequence == Self因为self[index(after: startIndex)..<endIndex]返回 a SubSequence,self除非Self(符合 的特定类型Collection)和它SubSequence的类型相同,否则不能分配给它。
Array的SubSequence类型是ArraySlice,不是Array,因此此扩展名不适用于Array.