Skip to content

Instantly share code, notes, and snippets.

@Noobish1
Created May 12, 2018 09:39
Show Gist options
  • Save Noobish1/cf029f84b206c1f8fe1b5384e24935f5 to your computer and use it in GitHub Desktop.
Save Noobish1/cf029f84b206c1f8fe1b5384e24935f5 to your computer and use it in GitHub Desktop.
Weird Collection behaviour
import UIKit
public struct NonEmptyArray<Element> {
fileprivate var elements: [Element]
public init(elements: Element...) {
self.elements = elements
}
public var count: Int {
return elements.count
}
public var first: Element {
return elements.first!
}
}
extension NonEmptyArray: Collection {
public typealias Index = Int
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count
}
public func index(after i: Int) -> Int {
return i + 1
}
}
// MARK: MutableCollection
extension NonEmptyArray: MutableCollection {
public subscript(_ index: Int) -> Element {
get {
return elements[index]
}
set {
elements[index] = newValue
}
}
}
let array = NonEmptyArray(elements: 1)
let first: Int! = array.first // Calls Collection.first
let otherFirst = array.first // Calls NonEmptyArray.first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment