swift4, general function : sequence(first:next:) issue - Out of bounds: index >= endIndex - swift4

I am learning Ray Wenderlich's LinkedList of Algorithm and data Structure
The code is OK:
let nodes = sequence(first: lhs.node) { $0?.next }
The code is not OK:
let nodes = sequence(first: lhs.node, next: { aNode -> Node<Value>? in
aNode?.next
})// The question is here
I want to know how to right the Swift gramma
To operator the LinkedList, the issue is here:
public struct LinkedList<Value> {
public var head: Node<Value>?
public var tail: Node<Value>?
public init() {}
public var isEmpty: Bool {
return head == nil
}
public mutating func push(_ value: Value) {
copyNodes()
head = Node(value: value, next: head)
if tail == nil {
tail = head
}
}
public mutating func append(_ value: Value) {
copyNodes()
guard !isEmpty else {
push(value)
return
}
tail!.next = Node(value: value)
tail = tail!.next
}
public func node(at index: Int) -> Node<Value>? {
var currentNode = head
var currentIndex = 0
while currentNode != nil && currentIndex < index {
currentNode = currentNode!.next
currentIndex += 1
}
return currentNode
}
private mutating func copyNodes() {
guard !isKnownUniquelyReferenced(&head) else {
return
}
guard var oldNode = head else {
return
}
head = Node(value: oldNode.value)
var newNode = head
while let nextOldNode = oldNode.next {
newNode!.next = Node(value: nextOldNode.value)
newNode = newNode!.next
oldNode = nextOldNode
}
tail = newNode
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
guard let head = head else {
return "Empty list"
}
return String(describing: head)
}
}
extension LinkedList: Collection {
public struct Index: Comparable {
public var node: Node<Value>?
static public func ==(lhs: Index, rhs: Index) -> Bool {
switch (lhs.node, rhs.node) {
case let (left?, right?):
return left.next === right.next
case (nil, nil):
return true
default:
return false
}
}
static public func <(lhs: Index, rhs: Index) -> Bool {
guard lhs != rhs else {
return false
}
var nodes = sequence(first: lhs.node) { $0?.next }
nodes = sequence(first: lhs.node, next: { (aNode) -> Node<Value>? in
aNode?.next
})// The question is here
// I overwrite the code to test it
return nodes.contains { $0 === rhs.node }
}
}
public var startIndex: Index {
return Index(node: head)
}
public var endIndex: Index {
return Index(node: tail?.next)
}
public func index(after i: Index) -> Index {
return Index(node: i.node?.next)
}
public subscript(position: Index) -> Value {
return position.node!.value
}
}
To Use the code:
example(of: "using collection") {
var list = LinkedList<Int>()
for i in 0...9 {
list.append(i)
}
print("Array containing last 3 elements: \(Array(list.suffix(3)))")
}
The LinkedList data structure
public class Node<Value> {
public var value: Value
public var next: Node?
public init(value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}
extension Node: CustomStringConvertible {
public var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) -> " + String(describing: next) + " "
}
}
Language sugar:
public func example(of description: String, action: () -> Void) {
print("---Example of \(description)---")
action()
print()
}
I checked apple's doc , https://developer.apple.com/documentation/swift/2015879-sequence
And have not found any nice idea.

Related

Init a FloatingPoint from a string

I am trying to convert a 2d array of Strings into my custom generic type Matrix:
func convert(_ arr: [[String]]) -> Matrix<Element> {
var m: Matrix<Element> = Matrix()
for row in arr {
var v: [Element] = []
for e in row {
let convE: Element = Element(string: e) // right here I'd like to implement something like that: Element(string: e)
v.append(convE)
}
m.vectors.append(Vector(v))
}
return m
}
The Matrix.Element does conform to the FloatingPoint protocol. Please tell me if you wish to see the Matrix struct but I think I haven't implemented anything that's important for this question other than that the generic Element type of Matrix does conform to the FloatingPoint protocol.
My problem is I want Element to be something like Float, Double... (any of the FloatingPoint types) but how can I initialize a FloatingPoint from a string? I tried:
extension FloatingPoint {
init(string: String) {
self.init(Int(string)!)
}
}
which obviously only works for strings like "1", "2"... and not "1.2", "3.541" and so on which I want.
Edit:(#Leo Dabus)
protocol DArray: Sequence {
associatedtype Component: FloatingPoint
}
extension DArray {
static func * <T: DArray>(lhs: Self, rhs: T) -> Vector<Component> {
let v = lhs as? Vector<Component> ?? rhs as! Vector<Component>
let m = lhs as? Matrix<Component> ?? rhs as! Matrix<Component>
return Vector(m.map { zip(v, $0).map(*).reduce(0, +) })
}
static func / <T: DArray>(lhs: Self, rhs: T) -> Vector<Component> {
let v = lhs as? Vector<Component> ?? lhs as! Vector<Component>
let m = lhs as? Matrix<Component> ?? lhs as! Matrix<Component>
return Vector(m.map { zip(v, $0).map(/).reduce(0, +) })
}
}
struct Vector<Component: FloatingPoint>: DArray {
var components: [Component]
var count: Int {
return components.count
}
init(_ Components: [Component] = []) {
self.components = Components
}
subscript(i: Int) -> Component {
get {
return components[i]
} set {
components[i] = newValue
}
}
static func + (lhs: Self, rhs: Self) -> Self {
return Vector(zip(lhs, rhs).map(+))
}
static func - (lhs: Self, rhs: Self) -> Self {
return Vector(zip(lhs, rhs).map(-))
}
static func * (lhs: Self, rhs: Self) -> Self {
return Vector(zip(lhs, rhs).map(*))
}
static func / (lhs: Self, rhs: Self) -> Self {
return Vector(zip(lhs, rhs).map(/))
}
func empty(of length: Int) -> Self {
return Vector(Array(repeating: 0, count: length))
}
}
struct Matrix<Component: FloatingPoint>: DArray {
var vectors: [Vector<Component>]
var nRows: Int {
return vectors.count
}
var nColumns: Int {
guard !vectors.isEmpty else { return 0 }
return vectors[0].count
}
var count: Int {
return vectors.count
}
init(_ vectors: [Vector<Component>] = []) {
self.vectors = vectors
}
subscript(r: Int) -> Vector<Component> {
get {
return vectors[r]
}
set {
vectors[r] = newValue
}
}
subscript(r: Int, c: Int) -> Component {
get {
return vectors[r][c]
}
set {
vectors[r][c] = newValue
}
}
}
Additionally I have my two structs conform to the Sequence protocol.
(Note: I am the OP)
What I came up with now is:
extension FloatingPoint {
public init?(string: String) {
if Self.self == Double.self {
self = Double(string) as! Self
} else if Self.self == Float.self {
self = Float(string) as! Self
} else if Self.self == Float80.self {
self = Float80(string) as! Self
} else {
return nil
}
}
}
It works for my use case but I was wondering whether it is a good way of achieving what I am looking for. So I'd be happy for someone to evaluate my solution. (#Leo Dabus)
You can extend FloatingPoint protocol and constrain the generic type to LosslessStringConvertible:
extension StringProtocol {
func floatingPoint<T: FloatingPoint>() -> T? where T: LosslessStringConvertible {
T(String(self))
}
}
Note that CGFloat does NOT conform to LosslessStringConvertible so you would need to implement a custom String initializer:
extension CGFloat: LosslessStringConvertible {
private static let formatter = NumberFormatter()
public init?(_ description: String) {
guard let number = CGFloat.formatter.number(from: description) as? CGFloat else { return nil }
self = number
}
}
let double: Double? = "2.7".floatingPoint() // 2.7
let float: Float? = "2.7".floatingPoint() // 2.7
let float80: Float80? = "2.7".floatingPoint() // 2.7
let cgfloat: CGFloat? = "2.7".floatingPoint() // 2.7
There is already an initializer for FloatingPoint types but to make your code work you need to conform your Matrix Component to LosslessStringConvertible.
Can you try something like this:
extension FloatingPoint where Self == Double {
init(string: String) {
self.init(Double(string)!)
}
}
extension FloatingPoint where Self == Float {
init(string: String) {
self.init(Float(string)!)
}
}
this should work as well
extension FloatingPoint {
init(string: String) {
self.init(Self(string)!)
}
}

How to implement doubly linked list in swift?

How can I implement a doubly linked list in Swift with all the operations like insert and deletion?
I know how to implement singly linked list but I can't find a way to make it a doubly linked list. I am a beginner in coding.
import UIKit
struct LinkedList<Value> {
var Head : node<Value>?
var Tail : node<Value>?
var isEmpty : Bool {
return Head == nil
}
// to add at the beginning of the list
mutating func push(_ value : Value) {
Head = node(value: value, nextNode: Head)
if Tail == nil {
Tail = Head
}
}
// to add at the end of the list
mutating func append(_ value : Value) {
guard !isEmpty else {
push(value)
return
}
let newNode = node(value: value)
Tail?.nextNode = newNode
Tail = newNode
}
//to find the node at particular index
func findNode(at index: Int) -> node<Value>? {
var currentIndex = 0
var currentNode = Head
while(currentNode != nil && currentIndex < index) {
currentNode = currentNode?.nextNode
currentIndex += 1
}
return currentNode
}
// to insert at a particular location
func insert(_ value : Value, afterNode : node<Value>) {
afterNode.nextNode = node(value: value, nextNode: afterNode.nextNode)
}
mutating func pop() -> Value? {
defer {
Head = Head?.nextNode
if isEmpty {
Head = nil
}
}
return Head?.value
}
mutating func removeLast() -> Value? {
guard let head = Head else {
return nil
}
guard head.nextNode != nil else {
return pop()
}
var previous = head
var current = head
while let next = current.nextNode {
previous = current
current = next
}
previous.nextNode = nil
Tail = previous
return current.value
}
mutating func remove(after node : node<Value>?) -> Value? {
defer {
if node === Tail {
Tail = node
}
node?.nextNode = node?.nextNode?.nextNode
}
return node?.nextNode?.value
}
}
extension LinkedList : CustomStringConvertible {
var description: String {
guard let linkedListHead = Head else {
return "Empty List"
}
return String(describing: linkedListHead)
}
}
class node<Value> {
var value : Value
var nextNode : node?
init(value : Value , nextNode : node? = nil) {
self.value = value
self.nextNode = nextNode
}
}
extension node : CustomStringConvertible {
var description: String {
guard let nextValue = nextNode else { return "\(value)" }
return "\(value) -> " + String(describing: nextValue) + " "
}
}
var listOfIntegers = LinkedList<Int>()
var listOfStrings = LinkedList<String>()
listOfIntegers.push(1)
listOfIntegers.push(3)
listOfIntegers.push(4)
listOfIntegers.append(6)
let nodeInfo = listOfIntegers.findNode(at: 1)!
listOfIntegers.insert(8, afterNode: nodeInfo)
print(listOfIntegers)
listOfStrings.push("hello")
listOfStrings.push("Sardar Ji!")
print(listOfStrings)
let index = 3
let node2 = listOfIntegers.findNode(at: index - 1)
listOfIntegers.remove(after: node2)
print(listOfIntegers)
I want to implement doubly linked list the same way and the output should be like this:
node1 <-> node2 <-> node3
//here is the full implementaion of doubly-linked-list in swift. updates will be appreciated.
import Foundation
struct DoublyLinkedList<DataItem> {
fileprivate var head : Node<DataItem>?
fileprivate var tail : Node<DataItem>?
var isEmpty : Bool {
return head == nil
}
//to add at the beginning
mutating func InsertAtBeginning(_ dataItem : DataItem) {
let node = Node(dataItem: dataItem, nextNode: head, previousNode: nil)
head?.previousNode = node
head = node
if tail == nil {
tail = head
}
}
//to add at the end
mutating func insertAtEnd(_ dataItem : DataItem) {
guard !isEmpty else {
InsertAtBeginning(dataItem)
return
}
let newNode = Node(dataItem: dataItem, nextNode: nil, previousNode: tail)
tail?.nextNode = newNode
//newNode.previousNode = tail
tail = newNode
}
//to insert at particular node
func insertParticularly(_ dataItem : DataItem , afterNode : Node<DataItem>) {
let node = Node(dataItem: dataItem)
afterNode.nextNode?.previousNode = node
node.nextNode = afterNode.nextNode
afterNode.nextNode = node
node.previousNode = afterNode
}
//to find a node at particular index
func findNode(at index : Int) -> Node<DataItem>? {
var currentIndex = 0
var currentNode = head
while currentNode != nil && currentIndex < index {
currentNode = currentNode?.nextNode
currentIndex += 1
}
return currentNode
}
//MARK:- remove functionality
//remove the first element
mutating func removeFirst() -> DataItem? {
defer {
head = head?.nextNode
if isEmpty {
head = nil
}
}
return head?.dataItem
}
// remove the last element
mutating func removeLast() -> DataItem? {
guard let headValue = head else {
return nil
}
guard headValue.nextNode != nil else {
return removeFirst()
}
var previous = headValue
var current = headValue
while let next = current.nextNode {
previous = current
current = next
}
previous.nextNode = nil
tail = previous
return current.dataItem
}
// remove from a specific location
mutating func removeAt(at node : Node<DataItem>?) -> DataItem? {
defer {
if node === tail {
removeLast()
}
node?.previousNode?.nextNode = node?.nextNode
node?.nextNode?.previousNode = node?.previousNode
}
return node?.nextNode?.dataItem
}
}
extension DoublyLinkedList : CustomStringConvertible {
var description : String {
guard let doublyLinkedListHead = head else { return "UnderFlow"}
//return String(describing: doublyLinkedListHead)
return doublyLinkedListHead.linkedDescription
}
}
class Node<DataItem> {
var dataItem : DataItem
var nextNode : Node?
var previousNode : Node?
init(dataItem : DataItem , nextNode : Node? = nil , previousNode : Node? = nil) {
self.dataItem = dataItem
self.nextNode = nextNode
self.previousNode = previousNode
}
}
extension Node : CustomStringConvertible {
var description: String {
return ((previousNode == nil) ? "nil" : "\(previousNode!.dataItem)") +
" <-> \(dataItem) <-> " +
((nextNode == nil) ? "nil" : "\(nextNode!.dataItem)")
}
var linkedDescription: String {
return "\(dataItem)" + ((nextNode == nil) ? "" : " <-> \(nextNode!.linkedDescription)")
}
}
var list = DoublyLinkedList<Int>()
list.InsertAtBeginning(4)
list.insertAtEnd(5)
list.insertAtEnd(4)
list.insertAtEnd(7)
list.insertAtEnd(2)
list.insertAtEnd(0)
list.description
let node1 = list.findNode(at: 3)
node1?.previousNode
list.head
Fundamentally, your problem is that you've got head and tail pointers in LinkedList, but node only has nextNode pointer. If node is the structure representing each item in the list, and if you want to be able to traverse the list in either direction, then each item needs a link to the next item and also the previous item. That's why they call it a "doubly linked list" after all.
Add a previousNode pointer to your node structure.
Go find every spot in your code where you modify a nextNode pointer and change the code to also maintain the previousNode pointer.

Successor of a node in a Binary Search Tree - Swift

Trying to solve the successor for a nod in a binary tree s.t. the tree
has the following successors: for 8 -> 10, 10 -> 12 and 14 -> 20
However, for 10 I'm returning nil (and, indeed for 14 I'm returning nil).
My algorithm is:
func inorderSucc(_ node: Node? = nil) -> Node? {
if (node == nil) {
return nil
} else {
if let rhn = node?.right {
return leftMostChild(rhn)
} else {
var q = node
var x = node?.parent
while (x != nil && x!.left != q) {
q = x
x = x?.parent
}
return x
}
}
}
func leftMostChild(_ n: Node) -> Node? {
var node = n
while (node.left != nil) {
node = node.left!
}
return node
}
Calling a tree:
class Node : CustomStringConvertible, Hashable{
var hashValue : Int { return data}
static func == (lhs: Node, rhs: Node) -> Bool {
return lhs.data == rhs.data
}
var data : Int
var left : Node?
var right : Node?
var parent : Node? = nil
var description: String {
return String(data) + (left?.description ?? "") + (right?.description ?? "")
}
init(_ data: Int) {
self.data = data
}
func insert(_ data: Int) {
if (data < self.data){
if let lhs = left {
lhs.insert(data)
}
else {
let lhNode = Node(data)
lhNode.parent = self
left = lhNode
}
}
else {
if let rhs = right {
rhs.insert(data)
}
else {
let rhNode = Node(data)
rhNode.parent = self
right = rhNode
}
}
}
}
inorderSearch is:
func inorderSearch (_ node: Node, _ data: Int) -> Node? {
if (node.data == data) {return node}
else {
if let lft = node.left {
return inorderSearch(lft, data)
}
if let rht = node.right {
return inorderSearch(rht, data)
}
}
return nil
}
And I insert the nodes as follows:
let gfg = Node(20)
gfg.insert(8)
gfg.insert(4)
gfg.insert(12)
gfg.insert(10)
gfg.insert(14)
gfg.insert(22)
print (gfg)
inorderSucc(inorderSearch(gfg, 8))
inorderSucc(inorderSearch(gfg, 10))
inorderSucc(inorderSearch(gfg, 14))
With the last three lines returning 10, nil and nil respectively. What's going wrong?
The issue stems from your search function. Think of what's happening if it doesn't find the actual number on the leftmost branch (child node(s) of the left node of the left node etc. ... of the root node). A possible correction would be to check for nil while exploring the left hand side, and then proceed to the right hand side of the subgraph as well.
func inorderSearch (_ node: Node, _ data: Int) -> Node? {
if (node.data == data) {return node}
else {
if let lft = node.left, let found = inorderSearch(lft, data) {
return found
} else if let rht = node.right, let found = inorderSearch(rht, data) {
return found
} else {
return nil
}
}
}
This code suppose that you don't have any preconception of what kind of graph this is. Otherwise, you could also check if the searched number is greater or lesser than your current node's value, and search in the left side or the right side accordingly.
You can do it like this:
First, declare class Node like so:
class Node {
let value: Int
var leftChield: Node?
var rightChield: Node?
init(value: Int, leftChield: Node?, rightChield: Node?) {
self.value = value
self.leftChield = leftChield
self.rightChield = rightChield
}
}
Then create all branches:
//Left Branch
let tenNode = Node(value: 10, leftChield: nil, rightChield: nil)
let fourteenNode = Node(value: 14, leftChield: nil, rightChield: nil)
let twelveNode = Node(value: 12, leftChield: tenNode, rightChield: fourteenNode)
let foureNode = Node(value: 4, leftChield: nil, rightChield: nil)
let eithNode = Node(value: 8, leftChield: foureNode, rightChield: twelveNode)
//Right Branch
let twentytwoNode = Node(value: 22, leftChield: nil, rightChield: nil)
// Root Node
let rootTwentyNode = Node(value: 20, leftChield: eithNode, rightChield: twentytwoNode)
Then create a function with logic:
func binarySearch(node: Node?, searchValue: Int) -> Bool {
if node == nil {
return false
}
if node?.value == searchValue {
return true
} else if searchValue < node!.value {
return binarySearch(node: node?.leftChield, searchValue: searchValue)
} else {
return binarySearch(node: node?.rightChield, searchValue: searchValue)
}
}
On the end, call the function like so and add rootNode with a value you want.
binarySearch(node: rootNode, searchValue: 50)

Generic Extension to Array Not Working

I've been playing around with Generics and Extensions to existing types in Swift 3. I wrote two generic Array functions that extends Array with find-and-replace methods, named replaced() and replace(). The replaced() function works as intended but the replace() function has a compile time error. Here is the code and a test of one of the methods.
extension Array {
func replaced<T: Equatable>(each valueToReplace: T, with newValue: T) -> [T] {
var newArray:[T] = []
for index:Int in 0..<self.count {
if let temp = self[index] as? T, temp == valueToReplace{
newArray.append(newValue)
}else{
newArray.append(self[index] as! T)
}
}
return newArray
}
mutating func replace<T: Equatable>(each valueToReplace: T, with newValue: T) {
for index:Int in 0..<self.count {
if let temp = self[index] as? T, temp == valueToReplace {
// FIXME: self[index] = newValue
}
}
return
}
}
var j = [1,2,3,4,3,6,3,8,9]
var newArray = j.replaced(each: 3, with: 0)
I get a compile time error on the second method, replace(), at the line commented out with "//FIXME:" annotation. The compile time error says, "Ambiguous reference to member 'subscript'".
How can I fix the replace() code so it works?
Give this a shot
extension Array where Element: Equatable {
func replaced (each valueToReplace: Element, with newValue: Element) -> [Element] {
var newArray = [Element]()
newArray.reserveCapacity(self.count)
for element in self {
let newElement = (element == valueToReplace) ? newValue : element
newArray.append(newElement)
}
return newArray
}
mutating func replace(each valueToReplace: Element, with newValue: Element) {
for (i, element) in self.enumerated() {
if element == valueToReplace { self[i] = newValue }
}
}
}
var j = [1,2,3,4,3,6,3,8,9]
var newArray = j.replaced(each: 3, with: 0)
It would be better to remove the redundancy by just making replaced delegate to replace:
extension Array where Element: Equatable {
func replaced(each valueToReplace: Element, with newValue: Element) -> [Element] {
var copy = self
copy.replace(each: valueToReplace, with: newValue)
return copy
}
mutating func replace(each valueToReplace: Element, with newValue: Element) {
for (i, element) in self.enumerated() {
if element == valueToReplace { self[i] = newValue }
}
}
}

Insertion-Order Dictionary (like Java's LinkedHashMap) in Swift?

Is there a standard swift class that is a Dictionary, but keeps keys in insertion-order like Java's LinkedHashMap? If not, how would one be implemented?
Didn't know of one and it was an interesting problem to solve (already put it in my standard library of stuff) Mostly it's just a matter of maintaining a dictionary and an array of the keys side-by-side. But standard operations like for (key, value) in od and for key in od.keys will iterate in insertion order rather than a semi random fashion.
// OrderedDictionary behaves like a Dictionary except that it maintains
// the insertion order of the keys, so iteration order matches insertion
// order.
struct OrderedDictionary<KeyType:Hashable, ValueType> {
private var _dictionary:Dictionary<KeyType, ValueType>
private var _keys:Array<KeyType>
init() {
_dictionary = [:]
_keys = []
}
init(minimumCapacity:Int) {
_dictionary = Dictionary<KeyType, ValueType>(minimumCapacity:minimumCapacity)
_keys = Array<KeyType>()
}
init(_ dictionary:Dictionary<KeyType, ValueType>) {
_dictionary = dictionary
_keys = map(dictionary.keys) { $0 }
}
subscript(key:KeyType) -> ValueType? {
get {
return _dictionary[key]
}
set {
if newValue == nil {
self.removeValueForKey(key)
}
else {
self.updateValue(newValue!, forKey: key)
}
}
}
mutating func updateValue(value:ValueType, forKey key:KeyType) -> ValueType? {
let oldValue = _dictionary.updateValue(value, forKey: key)
if oldValue == nil {
_keys.append(key)
}
return oldValue
}
mutating func removeValueForKey(key:KeyType) {
_keys = _keys.filter { $0 != key }
_dictionary.removeValueForKey(key)
}
mutating func removeAll(keepCapacity:Int) {
_keys = []
_dictionary = Dictionary<KeyType,ValueType>(minimumCapacity: keepCapacity)
}
var count: Int { get { return _dictionary.count } }
// keys isn't lazy evaluated because it's just an array anyway
var keys:[KeyType] { get { return _keys } }
// values is lazy evaluated because of the dictionary lookup and creating a new array
var values:GeneratorOf<ValueType> {
get {
var index = 0
return GeneratorOf<ValueType> {
if index >= self._keys.count {
return nil
}
else {
let key = self._keys[index]
index++
return self._dictionary[key]
}
}
}
}
}
extension OrderedDictionary : SequenceType {
func generate() -> GeneratorOf<(KeyType, ValueType)> {
var index = 0
return GeneratorOf<(KeyType, ValueType)> {
if index >= self._keys.count {
return nil
}
else {
let key = self._keys[index]
index++
return (key, self._dictionary[key]!)
}
}
}
}
func ==<Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
return lhs._keys == rhs._keys && lhs._dictionary == rhs._dictionary
}
func !=<Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
return lhs._keys != rhs._keys || lhs._dictionary != rhs._dictionary
}
Swift 5 version:
// OrderedDictionary behaves like a Dictionary except that it maintains
// the insertion order of the keys, so iteration order matches insertion
// order.
struct OrderedDictionary<KeyType: Hashable, ValueType> {
private var _dictionary: Dictionary<KeyType, ValueType>
private var _keys: Array<KeyType>
init() {
_dictionary = [:]
_keys = []
}
init(minimumCapacity: Int) {
_dictionary = Dictionary<KeyType, ValueType>(minimumCapacity: minimumCapacity)
_keys = Array<KeyType>()
}
init(_ dictionary: Dictionary<KeyType, ValueType>) {
_dictionary = dictionary
_keys = dictionary.keys.map { $0 }
}
subscript(key: KeyType) -> ValueType? {
get {
_dictionary[key]
}
set {
if newValue == nil {
self.removeValueForKey(key: key)
} else {
_ = self.updateValue(value: newValue!, forKey: key)
}
}
}
mutating func updateValue(value: ValueType, forKey key: KeyType) -> ValueType? {
let oldValue = _dictionary.updateValue(value, forKey: key)
if oldValue == nil {
_keys.append(key)
}
return oldValue
}
mutating func removeValueForKey(key: KeyType) {
_keys = _keys.filter {
$0 != key
}
_dictionary.removeValue(forKey: key)
}
mutating func removeAll(keepCapacity: Int) {
_keys = []
_dictionary = Dictionary<KeyType, ValueType>(minimumCapacity: keepCapacity)
}
var count: Int {
get {
_dictionary.count
}
}
// keys isn't lazy evaluated because it's just an array anyway
var keys: [KeyType] {
get {
_keys
}
}
var values: Array<ValueType> {
get {
_keys.map { _dictionary[$0]! }
}
}
static func ==<Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
lhs._keys == rhs._keys && lhs._dictionary == rhs._dictionary
}
static func !=<Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
lhs._keys != rhs._keys || lhs._dictionary != rhs._dictionary
}
}
extension OrderedDictionary: Sequence {
public func makeIterator() -> OrderedDictionaryIterator<KeyType, ValueType> {
OrderedDictionaryIterator<KeyType, ValueType>(sequence: _dictionary, keys: _keys, current: 0)
}
}
struct OrderedDictionaryIterator<KeyType: Hashable, ValueType>: IteratorProtocol {
let sequence: Dictionary<KeyType, ValueType>
let keys: Array<KeyType>
var current = 0
mutating func next() -> (KeyType, ValueType)? {
defer { current += 1 }
guard sequence.count > current else {
return nil
}
let key = keys[current]
guard let value = sequence[key] else {
return nil
}
return (key, value)
}
}
I didn't found way to make values 'lazy'.. need more research