Skip to content

Instantly share code, notes, and snippets.

@mtackes
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save mtackes/96a474f9b000687d9f72 to your computer and use it in GitHub Desktop.

Select an option

Save mtackes/96a474f9b000687d9f72 to your computer and use it in GitHub Desktop.
Swift subscripting
// 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