2016年1月13日水曜日

SwiftでのStringの最後の文字にアクセスするメモ

SwiftでのStringに関して、

Use the startIndex property to access the position of the first Character of a String. The endIndex property is the position after the last character in a String.
と、以下に書いてありました。
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

要するに、Stringの最後の文字にアクセスしようとしたら、endIndexというプロパティではアクセスできず、predecessor()というメソッドでアクセスせねばならぬとのこと。
なるほど。。

let lastChar = str[str.endIndex.predecessor()]

という感じで。

最後の文字を削除したければ

str.removeAtIndex(str.endIndex.predecessor())
でOK。

Stringに関するメモでした。