Skip to content

Instantly share code, notes, and snippets.

@scotteg
Last active July 22, 2022 21:41
Show Gist options
  • Save scotteg/8750e4bdaa1b21f22089 to your computer and use it in GitHub Desktop.
Save scotteg/8750e4bdaa1b21f22089 to your computer and use it in GitHub Desktop.
A Swift extension that adds a middle() method to Array using generics
protocol HasMiddleValue {
typealias ItemType
func middle() -> [ItemType]
}
extension Array: HasMiddleValue {
typealias ItemType = Generator.Element
func middle() -> [ItemType] {
guard count > 0 else {
return [ItemType]()
}
let middleIndex = count / 2
let middleArray: [ItemType]
if count % 2 != 0 {
middleArray = [self[middleIndex]]
} else {
middleArray = [self[middleIndex - 1], self[middleIndex]]
}
return middleArray
}
}
let bradyGirls = ["Marcia", "Janet", "Cindy"]
bradyGirls.middle()
let doubles = [1.1, 2, 3.3, 4, 5.5, 6]
doubles.middle()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment