17
14

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 5 で String Interpolation をカスタマイズする

Last updated at Posted at 2019-03-30

String Interpolation とは?

文字列リテラルの中に値を挿入(補間)できる機構のこと。
Swiftでは文字列リテラルの中に \(foo) という書き方でString以外の値を挿入(補間)できます。

  • Interpolation = 挿入・補間の意。
  • 語源的には inter(間) + polire(磨く) で「間に入れて修正する」というニュアンスがあります1
  • String Interpolation は「文字列補間」と訳されるのが一般的です2

let age = 31
print("You are \(age)")

-> You are 31

デフォルトの挙動を変える

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Int) {
        appendLiteral("XXX")
    }
}

let int = 10
let string = "number is \(int)"
print(string)

-> number is XXX

引数を渡して出力を変化させる

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Date, formatter: DateFormatter) {
        appendLiteral(formatter.string(from: value))
    }
}

let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
let string = "today is \(date, formatter: formatter)"
print(string)

-> today is 3/30/19, 1:22 PM

独自の型の出力を新しく定義する

struct User {
    let honorific: String
    let name: String
}

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: User) {
        appendLiteral("\(value.honorific)\(value.name)")
    }
}

let user = User(honorific: "Mr.", name: "Tom")
let string = "user is \(user)"
print(string)

-> user is Mr.Tom

環境

Apple Swift version 5.0 (swiftlang-1001.0.69 clang-1001.0.45.2)
Target: x86_64-apple-darwin18.2.0

参考

  1. https://eng-etymo.com/archives/685

  2. https://ja.wikipedia.org/wiki/%E6%96%87%E5%AD%97%E5%88%97%E8%A3%9C%E9%96%93

17
14
5

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
17
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?