> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/type/category/basic/string/str-i-str-i..less-than-j-str-i...j.md).

# str\[i], str\[i..\<j], str\[i...j]

{% tabs %}
{% tab title="str\[i]" %}
:point\_right: [replit](https://replit.com/@pegasusroe/string5#main.swift)

```swift
extension String {

    /// ⭐ example: `str[5]`
    public subscript(_ i: Int) -> String? {

        // ⭐ guard: non-empty string, non-negative index 
        guard !isEmpty, i >= 0 else { return nil }

        // ⭐ safe bound
        let bound = index(before: endIndex)     // ⭐ Note: `endIndex` is NOT safe

        // ⭐ guard: startIndex <= index < endIndex
        guard let index = index(startIndex, offsetBy: i, limitedBy: bound) else {
            return nil
        }

        // ⭐ Character -> String
        return String(self[index])
    }

    /// example: `str[2..<5]`
    public subscript(bounds: Range<Int>) -> String? {

        // ⭐ guard: empty string
        guard !isEmpty else { return nil }      // empty string -> nil

        // ⭐ guard: 0 <= m < n
        let (m, n) = (bounds.lowerBound, bounds.upperBound)
        guard 0 <= m, m < n else { return nil }        // negative index -> nil

        // ⭐ guard: i < endIndex, j <= endIndex
        let bound = index(before: endIndex)
        guard let i = index(startIndex, offsetBy: m, limitedBy: bound) else {
            return nil
        }
        guard let j = index(startIndex, offsetBy: n, limitedBy: endIndex) else {
            return nil
        }

        // i, j are in safe range
        return String(self[i..<j])
    }

    /// example: `str[2...5]`
    public subscript(bounds: ClosedRange<Int>) -> String? {

        // ⭐ guard: empty string
        guard !isEmpty else { return nil }      // empty string -> nil

        // ⭐ guard: 0 <= m < n
        let (m, n) = (bounds.lowerBound, bounds.upperBound)
        guard 0 <= m, m <= n else { return nil }        // negative index -> nil

        // ⭐ guard: i < endIndex, j <= endIndex
        let bound = index(before: endIndex)
        guard let i = index(startIndex, offsetBy: m, limitedBy: bound) else {
            return nil
        }
        guard let j = index(startIndex, offsetBy: n, limitedBy: bound) else {
            return nil
        }

        // i, j are in safe range
        return String(self[i...j])
    }
}
```

{% endtab %}

{% tab title="💈範例" %}
:point\_right: [replit](https://replit.com/@pegasusroe/string5#main.swift)

```swift
//       01234
let s = "Swift"
s[1]    // String?: "w"
s[5]    // nil

// half-open range
s[0..<3],               // Optional("Swi")
s[2..<5],               // Optional("ift")
s[1..<1],               // nil
s[1..<9],               // nil
s[-3..<2],              // nil

// closed range
s[0...3],               // Optional("Swif")
s[2...5],               // nil
s[1...1],               // Optional("w")
s[1...9],               // nil
s[-3...2],              // nil
```

{% endtab %}

{% tab title="👥 相關" %}

* [String.Index](/ios/swift/type/category/basic/string/string.index.md)
* [Subscripts](/ios/swift/subscripts.md)
  {% endtab %}

{% tab title="📘 手冊" %}

* Swift ⟩&#x20;
  * [Subscripts](https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html)
  * [Collections](https://developer.apple.com/documentation/swift/swift_standard_library/collections) ⟩&#x20;
    * [Range](https://developer.apple.com/documentation/swift/range)\<Bound> - (generic <mark style="color:red;">**struct**</mark>)
    * [BidirectionalCollection](https://developer.apple.com/documentation/swift/bidirectionalcollection) ⟩&#x20;
      * [subscript(\_:)](https://developer.apple.com/documentation/swift/bidirectionalcollection/2944568-subscript) - `arr[i..<j]`, `str[i..<j]` 都是 **override** 這個方法
        {% endtab %}

{% tab title="🗣 討論" %}

* ['subscript' is unavailable: cannot subscript String with a CountableClosedRange](https://stackoverflow.com/questions/45497705/subscript-is-unavailable-cannot-subscript-string-with-a-countableclosedrange)
  {% endtab %}
  {% endtabs %}
