Skip to content

Instantly share code, notes, and snippets.

@martineno
Created June 23, 2014 02:24
Show Gist options
  • Save martineno/edc3b42c95bf596259d0 to your computer and use it in GitHub Desktop.
Save martineno/edc3b42c95bf596259d0 to your computer and use it in GitHub Desktop.
An attempt at a Swift really const array
// Swift has the somewhat unusual const array semntatics in that a
// const array can still have its individual elements changed. I was thinking if there
// was a way to get the const behavior that one might expect, i.e. in a const array
// not only is the length of an array fixed, but also all of its elements.
//
// Here is my attempt:
struct ConstArray<T> {
var array: Array<T> = []
init(array: Array<T>) {
self.array = array.copy()
}
subscript(index: Int) -> T {
get {
return array[index]
}
}
}
// Use this my declaring an instance of it as a const, e.g.:
let ca = ConstArray(array: [1, 2, 3])
// now:
ca[2] // give us 3
ca[1] = 3 // fails, since to subscript setting exists
// Drawbacks
// 1. It will always make a copy of the array
// 2. To guarantee immutability, you *have* to store it in a constant (i.e. use the keyword let)
// 3. Its awkward to initialize
// 4. You can't actually use it in place of where you would use a regualar array, though this could
// potentially be fixed by implementing the Sequence protocol
@martineno
Copy link
Author

Well, given that Swift now has full value semantics for arrays, this shouldn't be needed...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment