{"id":50136932,"url":"https://github.com/brzzdev/swift-safe-subscript","last_synced_at":"2026-05-23T22:30:48.474Z","repository":{"id":357460795,"uuid":"1237066292","full_name":"brzzdev/swift-safe-subscript","owner":"brzzdev","description":"O(1) [safe:] subscript access for any Swift collection","archived":false,"fork":false,"pushed_at":"2026-05-12T21:45:10.000Z","size":11,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-12T23:05:52.725Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"unlicense","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/brzzdev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-12T20:59:54.000Z","updated_at":"2026-05-12T21:44:24.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/brzzdev/swift-safe-subscript","commit_stats":null,"previous_names":["brzzdev/swift-safe-subscript"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/brzzdev/swift-safe-subscript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brzzdev%2Fswift-safe-subscript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brzzdev%2Fswift-safe-subscript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brzzdev%2Fswift-safe-subscript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brzzdev%2Fswift-safe-subscript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/brzzdev","download_url":"https://codeload.github.com/brzzdev/swift-safe-subscript/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brzzdev%2Fswift-safe-subscript/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33415020,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-23T22:14:44.296Z","status":"ssl_error","status_checked_at":"2026-05-23T22:14:43.778Z","response_time":53,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-05-23T22:30:47.354Z","updated_at":"2026-05-23T22:30:48.460Z","avatar_url":"https://github.com/brzzdev.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# swift-safe-subscript\n\nA tiny Swift package that adds a `subscript(safe:)` to every `Collection` and `MutableCollection`. Out-of-bounds reads return `nil` instead of trapping; out-of-bounds writes are silent no-ops.\n\n```swift\nlet array = [1, 2, 3]\narray[safe: 0] // 1\narray[safe: 99] // nil\narray[safe: -1] // nil\n```\n\n## Installation\n\nAdd the package to your `Package.swift`'s dependencies:\n\n```swift\n.package(\n\turl: \"https://github.com/brzzdev/swift-safe-subscript.git\",\n\tfrom: \"1.0.0\",\n),\n```\n\nThen add the product to any target that needs it:\n\n```swift\n.product(\n\tname: \"SafeSubscript\",\n\tpackage: \"swift-safe-subscript\",\n),\n```\n\nOr in Xcode: **File → Add Package Dependencies…** and paste the repository URL.\n\n## Usage\n\nIt works on any `Collection`, regardless of the index type:\n\n```swift\nimport SafeSubscript\n\n// Array (Int index)\n[10, 20, 30][safe: 1] // Optional(20)\n[10, 20, 30][safe: 10] // nil\n\n// ArraySlice (non-zero startIndex)\nlet slice = [0, 1, 2, 3, 4][2...]\nslice[safe: 2] // Optional(2)\nslice[safe: 0] // nil (inside the array but outside the slice)\n\n// String / Substring (String.Index)\n\"hello\"[safe: \"hello\".startIndex] // Optional(\"h\")\n\"hello\"[safe: \"hello\".endIndex] // nil\n\n// Dictionary / Set (opaque Index)\nlet dict = [\"a\": 1, \"b\": 2]\ndict[safe: dict.startIndex] // Optional((key: \"a\", value: 1))\ndict[safe: dict.endIndex] // nil\n\n// Range\n(10..\u003c15)[safe: 12] // Optional(12)\n(10..\u003c15)[safe: 99] // nil\n```\n\n`MutableCollection` adds a setter. Writes outside the valid range — or assignments of `nil` — are no-ops:\n\n```swift\nvar array = [1, 2, 3]\narray[safe: 1] = 20 // [1, 20, 3]\narray[safe: 99] = 99 // [1, 20, 3] — unchanged\narray[safe: 1] = nil // [1, 20, 3] — unchanged\n```\n\n## Why not implement `subscript(safe:)` with `indices.contains`?\n\nThe obvious one-liner is to ask the collection itself whether the index is valid:\n\n```swift\nextension Collection {\n\tpublic subscript(safe index: Index) -\u003e Element? {\n\t\tindices.contains(index) ? self[index] : nil\n\t}\n}\n```\n\nThis is correct but loses badly on any collection where `indices.contains` is O(n) — which is most of them. Only `RandomAccessCollection`s with `Range\u003cInt\u003e` indices (`Array`, `Range`, `UnsafeBufferPointer`, …) get O(1) from `indices.contains`. For `String`, `Substring`, `Set`, `Dictionary`, and friends, `indices` returns a `DefaultIndices` that walks the collection linearly to answer `.contains`.\n\nThis package compares `index` against `startIndex` and `endIndex` directly:\n\n```swift\nextension Collection {\n\t@inlinable\n\tpublic subscript(safe index: Index) -\u003e Element? {\n\t\tindex \u003e= startIndex \u0026\u0026 index \u003c endIndex ? self[index] : nil\n\t}\n}\n```\n\nTwo `Comparable` comparisons. O(1) on every standard-library collection.\n\n## Benchmarks\n\nMeasured on Apple Silicon with Swift 6.3 in release mode, best of 15 trials. Both versions are compiled with `@inlinable`, given the same probe arrays (mixing in-bounds and out-of-bounds indices), and run through the same harness — so the only difference is the implementation of `subscript(safe:)` itself. Input values are runtime-perturbed so the optimizer can't constant-fold the loop.\n\n| Collection             | n     | `startIndex`/`endIndex` impl | `indices.contains` impl  | Speedup     |\n| :--------------------- | ----: | ---------------------------: | -----------------------: | ----------: |\n| `Array\u003cInt\u003e`           | 1 000 |                 3 560 ns/op  |              4 573 ns/op |       1.28× |\n| `String`               | 1 000 |                10 949 ns/op  |          1 612 572 ns/op |     147.28× |\n| `Dictionary\u003cInt, Int\u003e` |   500 |                   378 ns/op  |            297 646 ns/op |     788.47× |\n\nThe `Array` ratio is noise-dominated and varies run to run (typically 1.0–2.0×) because `Array.indices` is a `Range\u003cInt\u003e` with O(1) `.contains` — the absolute gap is only a few hundred nanoseconds across 10 000 probes. For everything backed by `DefaultIndices` (`String`, `Substring`, `Set`, `Dictionary`, …), the `indices.contains` implementation collapses to O(n) per lookup and the speedup is stable.\n\nReproduce locally:\n\n```sh\nswift run -c release SafeSubscriptBenchmarks\n```\n\n## Testing\n\n```sh\nswift test\n```\n\nThe suite covers `Array`, `ArraySlice` (non-zero `startIndex`), `ContiguousArray`, `String`, `Substring`, `Set`, `Dictionary`, `Range`, lazy/repeated wrappers, and `Int.min` / `Int.max` probes, plus mutable-set semantics for `MutableCollection`.\n\n## License\n\n[The Unlicense](LICENSE.md) — public domain, no attribution required.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrzzdev%2Fswift-safe-subscript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrzzdev%2Fswift-safe-subscript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrzzdev%2Fswift-safe-subscript/lists"}