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

String(format:)にはCVarArg...と[CVarArg]の2パターン存在する

Posted at

ほとんどの場合 CVarArg... のほうしか使わないと思うけど。

// まったく相応しくない例
let price = "5000兆"
let unit = "円"
let formatted = String(format: "%@%@欲しい!!", price, unit)

可変引数部分もラップした関数を用意したとき、こう書いちゃだめ。

// ❌意図した動作にならない
// argumentの中身は[CVarArg]であり、String(format:)には1つ目の可変引数と解釈されてしまう
func localized(format: String, _ arguments: CVarArg...) -> String {
    return String(
        format: NSLocalizedString(format, comment: ""),
        arguments
    )
}

arguments: キーを付けると [CVarArg]` を引数として取るので、こっちが正解。

// ✅
func localized(format: String, _ arguments: CVarArg...) -> String {
    return String(
        format: NSLocalizedString(format, comment: ""),
        arguments: arguments    // argumentsキーをつけて渡す
    )
}

ビルドエラーも出ないし、動作不定なので分かりづらいよね...

0
2
0

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
0
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?