Created
May 12, 2018 09:39
-
-
Save Noobish1/cf029f84b206c1f8fe1b5384e24935f5 to your computer and use it in GitHub Desktop.
Weird Collection behaviour
This file contains hidden or 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
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