9
9

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.

Swiftの文字列formatでargumentsを配列で指定するときに配列の長さが足りない場合のEXC_BAD_INSTRUCTIONを避ける

Last updated at Posted at 2015-10-27

StringにはFoundation内のextensionでイニシャライザに、init(format: String, arguments: [CVarArgType])が定義されていますが、init(format: String, _ arguments: CVarArgType...)と同様に、argumentsの配列数が書式指定子数を下回った場合クラッシュします。

String(format: "%@ + %@ = %@", arguments: [
    "1", "2", "3"
    ]) // => 1 + 2 = 3

String(format: "%@ + %@ = %@", arguments: [
    "1", "2", "3", "4", "5"
    ]) // => 1 + 2 = 3

String(format: "%@ + %@ = %@", arguments: [
    "1"
    ]) // EXC_BAD_INSTRUCTION

バグの早期発見につながって有り難いことかもですが、クラッシュするのはやり過ぎな場面(APNSの、(loc-)key(loc-)argsからクライアント側で文字列を作る場合など)もあるかと思います。

回避方法

NSStringのお力をちょっとだけお借りする方法しか思いつきませんでした。

let arguments = [
    "1"
    ] as [CVarArgType]
NSString(format: "%@ + %@ = %@", arguments: getVaList(arguments)) as String // => 1 + (null) = (null)

他にいい方法がありましたら教えて下さいm(_ _)m

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?