📑

StringのdropLast()とremoveLast()の違いを整理する

2021/01/19に公開

SwiftのStringにおいて、末尾にある文字を削除する操作として

  • dropLast()
  • removeLast()

が挙げられるかと思います。似たような名前なので、パッと見では違いが分かりづらいですが内部での挙動は全く異なります。

備忘も兼ねてまとめることにしました。2つのメソッドのドキュメントに沿ってまとめていきます。

dropLast(_:)

Returns a subsequence containing all but the specified number of final elements.

func dropLast(_ k: Int) -> Substring

末尾からk番目までの要素を除外した部分集合(subsequence)を返却値として返す とあります。

ここでdropLast()は対象の文字列から指定された末尾の範囲を除外された、「残された部分」をSubstring型の値として生成し、返却しています。したがって、対象の文字列(のインスタンス)では値の変更はされません。

let str = "abcdef"

print(str.dropLast()) // abcde
print(str) // abcdef

https://developer.apple.com/documentation/swift/string/2893517-droplast

removeLast(_:)

Removes and returns the last element of the collection.

@discardableResult mutating func removeLast() -> Character

collectionの最後の要素を除外し、除外された要素を返却する とあります。(Removesとreturnsの目的語があくまでもthe last element)

さらにメソッドの定義を見てみると

  • 返却値を使用しない場合もありうる (@discardableResult)
  • 対象とするインスタンスの値そのものに変更を加える (mutating)

ことがわかります。返却値が「除外された後のもの」ではなく「除外された要素そのもの」である点と対象のインスタンス自体に変更を加える点がdropLast()と大きく異なる点です。

var str2 = "abcdef" // mutating funcなので、letに対してremoveLast()は適用できない
print(str2.removeLast()) // f
print(str2) // abcde

var str3 = "abcdef"
str3.removeLast() // 返却値を演算に使わず、末尾要素の削除のみを行う
print(str3) // abcde

https://developer.apple.com/documentation/swift/string/2892866-removelast

参考

https://developer.apple.com/documentation/swift/string

Discussion