【问题标题】:Xcode Playground bug? "fatal error: Can't form a Character from an empty String"Xcode 游乐场错误? “致命错误:无法从空字符串形成字符”
【发布时间】:2017-05-19 07:31:43
【问题描述】:

使用以下代码,我在控制台中得到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 斯威夫特 3+

【问题讨论】:

标签: swift xcode swift-playground


【解决方案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)) {

【讨论】:

  • limitedBy: s.index(before: s.endIndex)
猜你喜欢
  • 2017-03-15
  • 2017-01-07
  • 2012-08-30
  • 2017-10-09
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多