Last active
July 22, 2022 21:41
-
-
Save scotteg/8750e4bdaa1b21f22089 to your computer and use it in GitHub Desktop.
A Swift extension that adds a middle() method to Array using generics
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
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