Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
12
Help us understand the problem. What are the problem?
@mishimay

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

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
12
Help us understand the problem. What are the problem?