Skip to content

Commit dfea1d6

Browse files
authored
Update Queue-Optimized.swift
1 parent 667d265 commit dfea1d6

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

Queue/Queue-Optimized.swift

+12-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public struct Queue<T> {
2323
}
2424

2525
public mutating func dequeue() -> T? {
26-
guard head < array.count, let element = array[head] else { return nil }
26+
guard let element = array[guarded: head] else { return nil }
2727

2828
array[head] = nil
2929
head += 1
@@ -45,3 +45,14 @@ public struct Queue<T> {
4545
}
4646
}
4747
}
48+
49+
extension Array {
50+
51+
subscript(guarded idx: Int) -> Element? {
52+
guard (startIndex..<endIndex).contains(idx) else {
53+
return nil
54+
}
55+
return self[idx]
56+
}
57+
58+
}

0 commit comments

Comments
 (0)