LoginSignup
7
5

More than 5 years have passed since last update.

SwiftのString.CharacterViewとそれをArray化したものの違い

Posted at

[swift] String.CharacterViewが使いづらいと思う、そんなあなたにArrayのおすすめ - Qiitaを拝読して気になることがあったので調べてみました。

let w = "\u{65}\u{301}"                 // "é" == e + アクセントマーク
let wcv = w.characters
let wcv_endIndex = wcv.endIndex         // 2

let wcv_a = Array(wcv)                  // ["é"]
let wcv_a_endIndex = wcv_a.endIndex     // 1

let wcv_c0 = wcv[wcv.index(wcv.startIndex, offsetBy: 0)]    // "é"
let wcv_c1 = wcv[wcv.index(wcv.startIndex, offsetBy: 1)]    // fatal error: Can't form a Character from an empty String

"é"のcharactersのendIndexは2ですがArrayにしたら1になりました。しかし文字を取得しようとするとfatal errorになりました。
\u{301}のような特殊文字の扱いが問題になるのでCharacterView.IndexはStrideableにできないということでしょうか?
詳しい方に解説をお願いしたいところです。

7
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5