LoginSignup
13
4

More than 5 years have passed since last update.

Swift4 Multi-Line String Literals

Posted at

はじめに

Swift4から複数行の文字列リテラルが導入されるので、試してみました。

開発環境

category Version
Swift 4.0
XCode 9.0 beta (9M136h)

とりあえずplaygroundで書いてみた。

playground
let multiLineStr = """
FirstLine
SecondLine
ThirdLine
“""

// -> "FirstLine\nSecondLine\nThirdLine"

複数行の文字列を表現できました!
一応、文字列比較もしてみました。

playground
import UIKit

let str = "FirstLine\nSecondLine\nThirdLine"

let multiLineStr = """
FirstLine
SecondLine
ThirdLine
"""

if str == multiLineStr {
    print("str is equal to multiLineStr.")
} else {
    print("str is not equal to multiLineStr.")
}

// -> str is equal to multiLineStr.

当然ですが、同じ!!
ただ、なんとなく読みにくい。。

playgroundの次は、プロジェクトで。

playgroundで動作確認できたので、次にプロジェクトを作成して同じコードを書いてみました。
(サンプルなので、とりあえずViewControllerに。)

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        multiLineString()
    }

    func multiLineString() {
        let str = "FirstLine\nSecondLine\nThirdLine"

        let multiLineStr = """
FirstLine
SecondLine
ThirdLine
"""

        if str == multiLineStr {
            print("str is equal to multiLineStr.")
        } else {
            print("str is not equal to multiLineStr.")
        }
    }
}

""”書いてreturn押したら、カーソル左端に行くし、
control + i (インデントの調整のショートカット)押しても、上記コードのままでした。

インデントはこれが正しいのでしょうか?!

さいごに

インデントはどうすべきなのかイマイチ分かりませんでしたが、
とりあえず、複数行の文字列リテラル使ってみました。

本記事内にコード全部書いてしまいましたが、Githubに作成したサンプルをあげてあります。
https://github.com/stv-yokudera/swift4-multi-line-string-literals

13
4
2

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
13
4