gpt4 book ai didi

ios - 如何符合 MutableCollection?

转载 作者:搜寻专家 更新时间:2023-10-31 22:58:49 28 4
gpt4 key购买 nike

我找不到有关如何符合 MutableCollection 的文档. Google 在该主题上完全空白。

示例,我想为 GMSPath 添加一致性/GMSMutablePath :

import CoreLocation
import GoogleMaps

extension GMSPath: RandomAccessCollection {

public var startIndex: Int {
return 0
}

public var endIndex: Int {
return count
}

public func index(before i: Int) -> Int {
return i-1
}

public func index(after i: Int) -> Int {
return i+1
}

public subscript(position: Int) -> CLLocationCoordinate2D {
return coordinate(at: UInt(position))
}
}

extension GMSMutablePath: MutableCollection { // Error!

public override subscript(position: Int) -> CLLocationCoordinate2D {
get {
return coordinate(at: UInt(position))
}
set {
replaceCoordinate(at: UInt(position), with: newValue)
}
}
}

Error: Type 'GMSMutablePath' does not conform to a) 'MutableIndexable', b) 'MutableCollection'.

MutableCollection 的文档状态:

To add conformance to the MutableCollection protocol to your own custom collection, upgrade your type’s subscript to support both read and write access.

我做到了。

MutableCollection 继承自 MutableIndexable,文档说明:

In most cases, it’s best to ignore this protocol and use the MutableCollection protocol instead, because it has a more complete interface.

嗯?

最佳答案

这里的问题是我还遵循了 RandomAccessCollection 而不仅仅是 Collection/MutableCollection。在那种情况下,与文档所 promise 的相反,我们要做的不仅仅是提供一个下标 setter 。具体来说,切片下标需要实现。

我最终得到了以下结果。典型化是必要的,因为编译器似乎并不总能推断出它们。

 extension GMSPath: RandomAccessCollection {

public typealias Index = Int
public typealias Indices = DefaultRandomAccessIndices<GMSPath>

public var startIndex: Index {
return 0
}

public var endIndex: Index {
return count
}

public func index(before i: Index) -> Index {
return i-1
}

public func index(after i: Index) -> Index {
return i+1
}

public subscript(position: Index) -> CLLocationCoordinate2D {
return coordinate(at: UInt(position))
}
}

extension GMSMutablePath: MutableCollection {

public subscript(bounds: Range<Index>) -> RandomAccessSlice<GMSPath> {
get { return .init(base: self, bounds: bounds) }
set {
assert(newValue.count == bounds.count)
newValue.enumerated().forEach { self[$0] = $1 }
}
}

public override subscript(position: Index) -> CLLocationCoordinate2D {
get { return coordinate(at: UInt(position)) }
set { replaceCoordinate(at: UInt(position), with: newValue) }
}
}

使用 Swift 的条件默认协议(protocol)实现,我发现很难找出究竟需要实现什么。

关于ios - 如何符合 MutableCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40097104/

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