2
2

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 5 years have passed since last update.

Swift5で文字列補間がカスタマイズ可能に

Last updated at Posted at 2019-03-29

Swift5がリリースされてざっと一通り目を通して、良くわからなかったのが

SE-0228 Fix ExpressibleByStringInterpolation
https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md

これです。

英文(読めない)をチラ見していると、以下のようにformat:で文字列補間の際にフォーマットを指定できるようになったのかな?と思ったのですが

// Use printf-style format strings:
"The price is $\(cost, format: "%.2f")"

// Use UTS #35 number formats:
"The price is \(cost, format: "¤###,##0.00")"

// Use Foundation.NumberFormatter, or a new type-safe native formatter:
"The price is \(cost, format: moneyFormatter)"

// Mimic String.init(_:radix:uppercase:)
"The checksum is 0x\(checksum, radix: 16)"

どうやら「フォーマットを指定できるようになった」のではなく、「フォーマットを指定するようなことも出来るようになった」という一例のようです。

自分で適当に組んだ感じでは

import UIKit

extension String.StringInterpolation {
    mutating func appendInterpolation<Value: CVarArg>(_ number: Value, format: String) {
        appendInterpolation(String(format: format, number))
    }
}

print("\(1.2456, format: "%.2f")") // 1.25

このようにString.StringInterpolation型のappendInterpolation関数をオーバーロードしてやることで、好きな拡張を行うことができるようになったようです。

使い分けに関しては他の方の記事に期待します😊

参考:
https://github.com/twostraws/whats-new-in-swift-5-0/blob/master/Whats-New-In-Swift-5-0.playground/Pages/Customizing%20string%20interpolation.xcplaygroundpage/Contents.swift

2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?