0
1

More than 1 year has passed since last update.

【Swift】StringをdropFirstできなかった時の解決策

Last updated at Posted at 2021-09-23

Swiftで文字列の最初の文字を削除したかったので、以下の処理を書いたがdropFirstが反映されない。

str = str.dropFirst()
str = str.dropFirst(1)
str = str.dropFirst(2)

3行ともdropFirstが反映されない。

エラー文はこんな感じ。

No 'dropFirst' candidates produce the expected contextual result type 'String'

ちなみにこの辺りの記事でもString型にdropFirstは適用されているが、自分の場合はなぜか反映されず。
コメントでご指摘いただいたようにdropFirstはSubstringにしか適用されないようです。

解決策

str = String(str.dropFirst())
str = String(str.dropFirst(1))
str = String(str.dropFirst(2))

Stringでキャストしたら処理が反映された。

Swiftのお役立ち情報

0
1
1

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