Xcode Playground bug? "fatal error: Can't form a Character from an empty String"

Xcode Playground bug? "fatal error: Can't form a Character from an empty String"

使用以下代码,我在控制台中得到 fatal error: Can't form a Character from an empty String。我看不出哪里或哪里做错了。

class Solution {
  func isValid(_ s: String) -> Bool {
    var dictionary = [Character: Character]()
    dictionary["("] = ")"
    dictionary["{"] = "}"
    dictionary["["] = "]"

    for (i, character) in s.characters.enumerated() {
      if i % 2 == 0 {
        if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.endIndex) {
          if dictionary[character] != s[idx] {
            return false
          }
        }
      }
    }

    return true
  }
}

var sol = Solution()
let test = "()[]["
print(sol.isValid(test))

Xcode 8.3.2 Swift3+

idx 太大时,问题出在表达式 s[idx] 上。当您将 idx 的计算更新为:

时,错误消失
if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.index(s.endIndex, offsetBy: -1)) {

或者,按照 Leo 的善意建议,

if let idx = s.index(s.startIndex, offsetBy: i + 1, limitedBy: s.index(before: s.endIndex)) {