2
1

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.

【Swift】JavaScriptやRubyみたいにStringを空文字でsplitしたい!

Last updated at Posted at 2020-07-15

こういうやつ

JavaScriptやRubyなら簡単。

"Hello, World".split('') // -> ["H", "e", "l", "l", "o", "," ...]

String#split(separator: Character)じゃダメなの?

"Hello, World".split(separator: "")
// Error: Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

そもそも実行できない。

String#components(separatedBy separator: T)

"Hello, World".components(separatedBy: "") // -> ["Hello, World"]

お、惜しい!(惜しくない)

正解 → Array(_ s: Sequence)

Array("Hello, World") // -> ["H", "e", "l", "l", "o", "," ...]

というわけで、Arrayのイニシャライザが使えるようです。
いざ調べても、たどり着くのに苦労したので記事にしてみました。

参考

Convert Swift string to array
https://stackoverflow.com/questions/25921204/convert-swift-string-to-array

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?