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
関数をオーバーロードしてやることで、好きな拡張を行うことができるようになったようです。
使い分けに関しては他の方の記事に期待します😊