1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Stringをindex指定でCharacterを安全に取得する

Posted at

環境
Swift 5.3.2

StringはCollectionに準拠しているので元々 text[position] でアクセスできますが、subscriptの引数に指定できるものはString.Indexという型なのでIntを指定する事はできません。
そのため以下のextensionを記述することでInt型でCharacterを取得することができます。

extension StringProtocol {
    subscript(offset: Int) -> Character? {
        guard offset < count else { return nil }
        let index = self.index(startIndex, offsetBy: offset)
        return startIndex <= index && index < endIndex ? self[index] : nil
    }
}
1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?