Last active
August 29, 2015 14:10
-
-
Save mtackes/96a474f9b000687d9f72 to your computer and use it in GitHub Desktop.
Swift subscripting
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
| // A simple data source containing basic string 'notes' | |
| class Notes { | |
| private var notesArray = [String]() | |
| // Get & Set with some safety logic | |
| subscript(index: Int) -> String { | |
| // `note` arg is implicitly String (subscript return type) | |
| set (note) { | |
| if index < 0 { | |
| notesArray.insert(note, atIndex: 0) | |
| } | |
| else if index < notesArray.count { | |
| notesArray[index] = note | |
| } | |
| else { | |
| notesArray.append(note) | |
| } | |
| } | |
| get { | |
| if index < notesArray.count { | |
| return notesArray[index] | |
| } else { | |
| return "" | |
| } | |
| } | |
| } | |
| // Get only with no safety (because I was lazy) | |
| subscript(range: Range<Int>) -> String { | |
| return ", ".join(notesArray[range]) | |
| } | |
| } | |
| var notes = Notes() | |
| notes[0] = "First note" | |
| println(notes[0]) // "My first note" | |
| notes[1] = "Second note" | |
| notes[-1] = "New first note" | |
| println(notes[0]) // "New first note" | |
| println(notes[30]) // "" | |
| println(notes[1...2]) // "My first note, Second note" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment