0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】競プロでString型の文字列をArrayにする際に「No exact matches in call to intializer」エラーを引き起こさないためにすること

Posted at

エラー

  • 2ヶ月ぶりくらいに競技プログラミングに取り組んだら結構忘れていたので
  • 文字列 S を受け取りArrayに変換した時に発生する下記のエラーについて
No exact matches in call to intializer

解決策

// NG
let array_s = Array(s)

// OK
let array_s: [String] = Array(s).map{ String($0) }

誤解を招きそうなので補足します。
・NGのコードでも動作しますし、文法上問題はありません。
・今回のコードはreadLineで得た文字列がCharacter型で格納されていたために、その後のコードでコンパイルエラーが発生したものとなります。その前提で読み進めていただければと思います。

ポイント

① [String]型の配列であることを明示的に示しておく

[String]
  • Swiftは型推論が強力な言語であるが、きちんと明示的に示しておくに越したことはない。

map関数を用いて各要素をStringに変換しておく

.map{String($0)}
  • 高級関数mapを用いることで、配列の各要素に一括で特定の処理を適用することができる。
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?