gpt4 book ai didi

arrays - 为什么 popFirst 抛出错误,但 removeFirst 有效?

转载 作者:搜寻专家 更新时间:2023-10-30 23:12:02 25 4
gpt4 key购买 nike

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()
}
}

我为 popFirst 得到的错误是:

cannot use mutating member on immutable value: 'self' is immutable

两者都是popFirstremoveFirst被标记为 mutating 并且返回和 T?。那为什么它不起作用?

编辑: 正如其他人评论的那样,这似乎是某种错误。已在论坛中讨论过here .

编辑:仍然发生在 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!
^

你得到这个错误是因为 popFirst没有为所有 Collection 定义秒。它仅在 Collection 时定义是自己的SubSequence类型。 Here's the implementation :

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
}
}

扩展需要 SubSequence == Self . Self (大写 S)是 self 的类型(带有小写的 s)。这是您正在调用的类型 popFirst .在您的代码中,SelfArray<T> , 也拼写为 [T] .

popFirst 的这一行需要约束编译:

self = self[index(after: startIndex)..<endIndex]

^__^ ^_______________________________________^
| |
| This is a SubSequence.
|
This is a Self.

self[index(after: startIndex)..<endIndex]SubSequence .

Swift 只能分配一个 SubSequenceSelf如果它知道 Self == SubSequence .

ArraySubSequence类型是 ArraySlice .自 ArraySliceArray 的类型不同, 此扩展不适用于 Array .

关于arrays - 为什么 popFirst 抛出错误,但 removeFirst 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com