LoginSignup
12
13

More than 5 years have passed since last update.

Swift / 文字列を1行ずつ抜き出す

Posted at

String.enumerateLinesを使う

テキストファイルから文字列を読み込んだ時等に役立つと思います。
定義は下記

String.enumerateLines
func enumerateLines(body: (line: String, inout stop: Bool) -> ())

サンプルコード

enumerateLinesの引数をクロージャで記述したサンプルコードです

文字列を1行ずつ抜き出す
var text: String = "hogehoge\npiyopiyp\nfugafuga"

var lineIndex = 1

//1行ごとに文字列を抜き出す
text.enumerateLines{
    line, stop in

    //下記に1行ごとに行いたい動作を記述
    println("\(lineIndex) : \(line)")
    lineIndex += 1
}

出力結果
1 : hogehoge
2 : piyopiyp
3 : fugafuga
12
13
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
12
13