サポートされている Swift 文字列フォーマット指定子は何ですか? 質問する

サポートされている Swift 文字列フォーマット指定子は何ですか? 質問する

Swift では、書式指定子を使用して文字列をフォーマットできます。

// This will return "0.120"
String(format: "%.03f", 0.12)

しかし、公式ドキュメントには、サポートされているフォーマット指定子や、次のようなテンプレートの作成方法に関する情報やリンクは提供されていません"%.03f"https://developer.apple.com/documentation/swift/string/3126742-init

そこにはこうだけ書いてある。

指定された書式文字列をテンプレートとして使用して初期化された String オブジェクトを返します。残りの引数の値はこれに置き換えられます。

ベストアンサー1

Swift でのフォーマットのフォーマット指定子はObjective-CフォーマットStringのフォーマット指定子と同じで、それ自体がformat のフォーマット指定子と同一であり、Apple ドキュメントのアーカイブの奥深くに埋もれています (両方のページの内容は同じで、どちらも元々は 2002 年以前のものです)。NSStringCFString

しかし、このドキュメントページ自体は不完全であり、例えば精度指定子と指定子は言及されていない。実際には、IEEE printf 仕様 (2004 年版第 6 版)は、それ自体が ISO C 標準に準拠しています。したがって、これらの指定子は、 Objective-C オブジェクトの指定子と、十分に文書化されていない、、指定子および長さ修飾子をprintf追加した、 C のものと同一であるはずです。%@%D%U%Oq


指定子

各変換仕様は、「%」文字または文字シーケンス「%n$」によって開始されます。

nパラメータのインデックスです。例:

String(format: "%2$@ %1$@", "world", "Hello")

書式指定子

%@ Objective-C オブジェクト。使用可能な場合は descriptionWithLocale: によって返される文字列として出力され、それ以外の場合は description として出力されます。

実際には、Swift の型もいくつか使用できますが、CVarArg プロトコルに準拠するためには標準ライブラリ内で定義する必要があり、Objective-C オブジェクトへのブリッジをサポートする必要があると思います。https://developer.apple.com/documentation/foundation/object_runtime/classes_bridged_to_swift_standard_library_value_types

String(format: "%@", ["Hello", "world"])

%% '%' キャラクター。

String(format: "100%% %@", true.description)

%d、%i 符号付き 32 ビット整数 (int)。

String(format: "from %d to %d", Int32.min, Int32.max)

%u、%U、%D 符号なし 32 ビット整数 (unsigned int)。

String(format: "from %u to %u", UInt32.min, UInt32.max)

%x 符号なし 32 ビット整数 (unsigned int)。0 ~ 9 の数字と小文字の a ~ f を使用して 16 進数で印刷されます。

String(format: "from %x to %x", UInt32.min, UInt32.max)

%X 符号なし 32 ビット整数 (unsigned int)。0 ~ 9 の数字と大文字の A ~ F を使用して 16 進数で印刷されます。

String(format: "from %X to %X", UInt32.min, UInt32.max)

%o、%O 符号なし 32 ビット整数 (unsigned int)、8 進数で印刷されます。

String(format: "from %o to %o", UInt32.min, UInt32.max)

%f 64 ビット浮動小数点数 (double)、10 進表記で出力されます。"inf"、"infinity"、または "nan" が生成されます。

String(format: "from %f to %f", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%F 64 ビット浮動小数点数 (double)、10 進表記で出力されます。"INF"、"INFINITY"、または "NAN" が生成されます。

String(format: "from %F to %F", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%e    64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent.

String(format: "from %e to %e", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%E    64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent.

String(format: "from %E to %E", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%g    64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.

String(format: "from %g to %g", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%G    64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.

String(format: "from %G to %G", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%c    8-bit unsigned character (unsigned char).

String(format: "from %c to %c", "a".utf8.first!, "z".utf8.first!)

%C    16-bit UTF-16 code unit (unichar).

String(format: "from %C to %C", "爱".utf16.first!, "终".utf16.first!)

%s    Null-terminated array of 8-bit unsigned characters.

"Hello world".withCString {
    String(format: "%s", $0)
}

%S    Null-terminated array of 16-bit UTF-16 code units.

"Hello world".withCString(encodedAs: UTF16.self) {
    String(format: "%S", $0)
}

%p    Void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x.

var hello = "world"
withUnsafePointer(to: &hello) {
    String(format: "%p", $0)
}

%n    The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of the fprintf() functions.

The n format specifier seems unsupported in Swift 4+

%a    64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent.

String(format: "from %a to %a", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

%A    64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent.

String(format: "from %A to %A", Double.leastNonzeroMagnitude, Double.greatestFiniteMagnitude)

Flags

'    The integer portion of the result of a decimal conversion ( %i, %d, %u, %f, %F, %g, or %G ) shall be formatted with thousands' grouping characters. For other conversions the behavior is undefined. The non-monetary grouping character is used.

The ' flag seems unsupported in Swift 4+

-    The result of the conversion shall be left-justified within the field. The conversion is right-justified if this flag is not specified.

String(format: "from %-12f to %-12d.", Double.leastNonzeroMagnitude, Int32.max)

+    The result of a signed conversion shall always begin with a sign ( '+' or '-' ). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified.

String(format: "from %+f to %+d", Double.leastNonzeroMagnitude, Int32.max)

<space>    If the first character of a signed conversion is not a sign or if a signed conversion results in no characters, a <space> shall be prefixed to the result. This means that if the <space> and '+' flags both appear, the <space> flag shall be ignored.

String(format: "from % d to % d.", Int32.min, Int32.max)

# 値を別の形式に変換することを指定します。o 変換の場合、結果の最初の桁が 0 になるように (必要な場合) 精度を上げます。x または X 変換指定子の場合、非ゼロの結果には 0x (または 0X) がプレフィックスとして付きます。a、A、e、E、f、F、g、および G 変換指定子の場合、小数点文字の後に数字が続かなくても、結果には常に小数点文字が含まれます。このフラグがない場合、小数点文字は、数字が続く場合にのみこれらの変換の結果に表示されます。g および G 変換指定子の場合、通常どおり、結果から末尾のゼロは削除されません。他の変換指定子の場合、動作は未定義です。

String(format: "from %#a to %#x.", Double.leastNonzeroMagnitude, UInt32.max)

0 d、i、o、u、x、X、a、A、e、E、f、F、g、および G 変換指定子の場合、先頭のゼロ (符号または基数の指定に続く) がフィールド幅にパディングするために使用されます。スペースのパディングは実行されません。 '0' フラグと '-' フラグの両方が表示された場合、 '0' フラグは無視されます。 d、i、o、u、x、および X 変換指定子の場合、精度が指定されていると、 '0' フラグは無視されます。 '0' フラグと '" フラグの両方が表示された場合、ゼロ パディングの前にグループ化文字が挿入されます。 その他の変換の場合、動作は未定義です。

String(format: "from %012f to %012d.", Double.leastNonzeroMagnitude, Int32.max)

幅修飾子

変換された値のバイト数がフィールド幅より少ない場合、デフォルトでは左側にスペースが埋め込まれます。フィールド幅に左揃えフラグ ( '-' ) が指定されている場合は、右側にスペースが埋め込まれます。フィールド幅は、アスタリスク ( '*' ) または 10 進整数の形式を取ります。

String(format: "from %12f to %*d.", Double.leastNonzeroMagnitude, 12, Int32.max)

精度修飾子

d、i、o、u、x、および X 変換指定子に表示される最小桁数、a、A、e、E、f、および F 変換指定子の基数文字の後に表示される桁数、g および G 変換指定子の最大有効桁数、または s および S 変換指定子の文字列から出力される最大バイト数を指定するオプションの精度。精度は、ピリオド ('.') の後にアスタリスク ('*') またはオプションの 10 進数字文字列が続く形式になります。この場合、ヌル数字文字列は 0 として扱われます。精度が他の変換指定子と共に使用される場合、動作は未定義です。

String(format: "from %.12f to %.*d.", Double.leastNonzeroMagnitude, 12, Int32.max)

長さ修飾子

h 後続の d、o、u、x、または X 変換指定子が short または unsigned short 引数に適用されることを指定する長さ修飾子。

String(format: "from %hd to %hu", CShort.min, CUnsignedShort.max)

hh 後続の d、o、u、x、または X 変換指定子が signed char または unsigned char 引数に適用されることを指定する長さ修飾子。

String(format: "from %hhd to %hhu", CChar.min, CUnsignedChar.max)

l 後続の d、o、u、x、または X 変換指定子が long または unsigned long 引数に適用されることを指定する長さ修飾子。

String(format: "from %ld to %lu", CLong.min, CUnsignedLong.max)

ll、q 後続の d、o、u、x、または X 変換指定子が long long または unsigned long long 引数に適用されることを指定する長さ修飾子。

String(format: "from %lld to %llu", CLongLong.min, CUnsignedLongLong.max)

L 長さ修飾子。後続の a、A、e、E、f、F、g、または G 変換指定子が long double 引数に適用されることを指定します。

formatSwift 4以降ではCLongDouble引数を渡すことができませんでした

z 後続の d、o、u、x、または X 変換指定子が size_t に適用されることを指定する長さ修飾子。

String(format: "from %zd to %zu", size_t.min, size_t.max)

t 長さ修飾子。後続の d、o、u、x、または X 変換指定子が ptrdiff_t に適用されることを指定します。

String(format: "from %td to %tu", ptrdiff_t.min, ptrdiff_t.max)

j 後続の d、o、u、x、または X 変換指定子が intmax_t または uintmax_t 引数に適用されることを指定する長さ修飾子。

String(format: "from %jd to %ju", intmax_t.min, uintmax_t.max)

おすすめ記事