From e9918a94efb963d7f4aa227f856f9a82b34463ad Mon Sep 17 00:00:00 2001 From: Jacob Pritchett Date: Sat, 19 Nov 2022 16:55:22 -0700 Subject: [PATCH] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index bde7a60..ddcd0e2 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,14 @@ Well, here's where this tool comes in. Now, when using the `safe: ` prefix on your subscripts when accessing indices in an array, you're now returned an optional, and nonexistent results return nil. This effectively matches the behavior of Swift Dictionaries, for example. +```Swift +let array = [1, 2, 3] + +guard let value = array[safe: 3] else { // Oops! The index here only goes up to 2. + return // Fail gracefully +} +``` + As for why this isn't the default behavior in Swift, I imagine it's for backwards compatibility reasons. It's not what I prefer, though, hence why I made this. Go ahead, `guard let` your arrays to your Swifty heart's content! 🧡