Conforming to Collection
with String
as Key
Dear Swift Community,
I would like some advice on making a Dictionary
-like structure conform to Collection
. The difference between this structure and Dictionary
is that the structure's key is always a String
, while a Dictionary
's Key
only has to conform to Hashable
.
Let's say we have this structure:
/// A table in a TOML document.
public class TOMLTable: Sequence, IteratorProtocol {
public var keys: [String] { ... }
public var values: [TOMLValue] { ... }
public var count: Int { ... }
public var isEmpty: Bool { ... }
public init(...) { ... }
public func contains(key: String) -> Bool { ... }
public func contains(element: TOMLValueConvertible) -> Bool { ... }
func insert(_ value: TOMLValueConvertible, at key: String { ... }
func remove(at key: String) -> TOMLValueConvertible? { ... }
// For conforming to Sequence and IteratorProtocol
func next() -> (String, TOMLValueConvertible)? { ... }
public subscript(key: String) -> TOMLValueConvertible? {
get { ... }
set(value) { ... }
}
...
}
With some modifications, the insert(_:at:)
, contains(element:)
, and remove(at:)
functions, and the subscript
can be used to conform to Collection
. The problem is that associatedtype Index
requirement in Collection
seems to only work with an Int
-based index, and most the functions and properties that use Index
seem to be make for an Index
of Int
. For example, the indices
property is a Range
of Index
, but you cannot make a Range
from a String
. Is there another way to conform to Collection
? Or is there another protocol TOMLTable
should conform to?
Jeff