Xcode Playground bug? "致命错误:无法从空字符串"形成一个字符

时间:2017-05-18 23:09:08

标签: swift xcode swift-playground

使用以下代码,我在控制台中获得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 Swift 3 +

1 个答案:

答案 0 :(得分:1)

s[idx]太大时,问题来自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)) {