Help us understand the problem. What is going on with this article?

Swift 5 で String Interpolation をカスタマイズする

More than 1 year has passed since last update.

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

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした