Skip to content

Instantly share code, notes, and snippets.

@eneko
Last active July 29, 2018 12:21
Show Gist options
  • Save eneko/3ec52e4f2d05434e28b2 to your computer and use it in GitHub Desktop.
Save eneko/3ec52e4f2d05434e28b2 to your computer and use it in GitHub Desktop.
Linked List in Swift
/// A list is either empty or it is composed of a first element (head)
/// and a tail, which is a list itself.
///
/// See http://www.enekoalonso.com/projects/99-swift-problems/#linked-lists
class List<T> {
var value: T
var nextItem: List<T>?
convenience init?(_ values: T...) {
self.init(Array(values))
}
init?(_ values: [T]) {
guard let first = values.first else {
return nil
}
value = first
nextItem = List(Array(values.suffix(from: 1)))
}
}
@scott-lydon
Copy link

scott-lydon commented Feb 4, 2018

(Swift 4 warning for line 9) Parameters may not have the 'var' specifier. I like your 99 problems website btw.

@eneko
Copy link
Author

eneko commented Feb 19, 2018

Hey Scott, thank you for your feedback. It is updated to Swift 4 now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment