forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce basic Stack type (realm#4922)
- Loading branch information
1 parent
46ff727
commit c241935
Showing
2 changed files
with
65 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
/// A basic stack type implementing the LIFO principle - only the last inserted element can be accessed and removed. | ||
struct Stack<Element> { | ||
private var elements = [Element]() | ||
|
||
var isEmpty: Bool { | ||
elements.isEmpty | ||
} | ||
|
||
var count: Int { | ||
elements.count | ||
} | ||
|
||
mutating func push(_ element: Element) { | ||
elements.append(element) | ||
} | ||
|
||
@discardableResult | ||
mutating func pop() -> Element? { | ||
elements.popLast() | ||
} | ||
|
||
func peek() -> Element? { | ||
elements.last | ||
} | ||
} | ||
|
||
extension Stack: CustomDebugStringConvertible where Element == CustomDebugStringConvertible { | ||
var debugDescription: String { | ||
let intermediateElements = count > 1 ? elements[1 ..< count - 1] : [] | ||
return """ | ||
Stack with \(count) elements: | ||
first: \(elements.first?.debugDescription ?? "") | ||
intermediate: \(intermediateElements.map(\.debugDescription).joined(separator: ", ")) | ||
last: \(peek()?.debugDescription ?? "") | ||
""" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters