2017-05-18 8 views
0

次のコードでは、コンソールにfatal error: Can't form a Character from an empty Stringが表示されます。私はどこで、何が間違っているのか分かりません。Xcode Playgroundのバグ? 「致命的なエラー:空の文字列から文字を作成できません」

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+

+0

がhttp://stackoverflow.com/q/42958011/2976878の比較:あなたがidxの計算を更新するときにエラーが消えます'limitedBy:'パラメータは*包括的*上限であるため、 'endIndex'(これは終わりのインデックスを過ぎています)で文字列を添字にしようとしています。 – Hamish

答えて

1

問題はidxが大きすぎる表現s[idx]からです。 -

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

か、など親切にレオが提案し、

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

'limitedBy:s.index(前:s.endIndex)' –

関連する問題