Created
November 20, 2017 19:32
-
-
Save asmallteapot/b994e7f6bf0d80b46abd0af158039b61 to your computer and use it in GitHub Desktop.
Example of using ranges with arrays in Swift 4
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
import Foundation | |
/// https://developer.apple.com/documentation/swift/range | |
enum NamedService: String { | |
case altamontCorridor | |
case californiaZephyr | |
case caltrain | |
case capitolCorridor | |
case coaster | |
case coastDaylight | |
case coastStarlight | |
case metrolink | |
case napaValley | |
case pacificSurfliner | |
case sanJoaquins | |
case skunkTrain | |
case sonomaMarin | |
case sprinter | |
static let all: [NamedService] = [ | |
.altamontCorridor, | |
.californiaZephyr, | |
.caltrain, | |
.capitolCorridor, | |
.coaster, | |
.coastDaylight, | |
.coastStarlight, | |
.metrolink, | |
.napaValley, | |
.pacificSurfliner, | |
.sanJoaquins, | |
.skunkTrain, | |
.sonomaMarin, | |
.sprinter, | |
] | |
} | |
let startIndex = NamedService.all.startIndex | |
let endIndex = NamedService.all.endIndex | |
guard let coasterIndex = NamedService.all.index(of: .coaster) else { | |
fatalError("couldn't find index for .coaster") | |
} | |
let afterCoasterIndex = coasterIndex.advanced(by: 1) | |
NamedService.all[startIndex...coasterIndex] | |
/* altamontCorridor | |
* californiaZephyr | |
* caltrain | |
* capitolCorridor | |
* coaster | |
*/ | |
NamedService.all[afterCoasterIndex..<endIndex] | |
/* | |
* coastDaylight | |
* coastStarlight | |
* metrolink | |
* napaValley | |
* pacificSurfliner | |
* sanJoaquins | |
* skunkTrain | |
* sonomaMarin | |
* sprinter | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment