📜  string.format swift (1)

📅  最后修改于: 2023-12-03 14:47:43.820000             🧑  作者: Mango

String Format in Swift

String.format is a powerful function in Swift that allows you to format strings in a variety of ways. With String.format, you can easily add variables, dates, and even emoji to your strings based on your desired output.

Basic Syntax

The basic syntax for using String.format is as follows:

let formattedString = String(format: "String with %d and %@", 1, "format")

In the above example, "%d" specifies a decimal value that is replaced with the number 1, and "%@" specifies a placeholder for a string that is replaced with the word "format".

String Formatting Options
  • %@: Inserts a string.
  • %d or %i: Inserts a signed integer.
  • %u: Inserts an unsigned integer.
  • %f: Inserts a floating-point number.
  • %e or %E: Inserts a floating-point number in scientific notation.
  • %g or %G: Inserts a floating-point number, using %f or %e (whichever is shorter).
  • %c: Inserts a character.
  • %p: Inserts a pointer.
  • %%: Inserts a percentage sign.
Advanced String Formatting
Padding

You can use String.format to add padding to your strings. Padding is useful when you want to make sure that your output lines up correctly. For example:

let paddedString = String(format: "|%5d|", 1)
// paddedString is "|    1|"

In the above example, %5d specifies that the integer should take up 5 spaces. Since the integer 1 only takes up one space, the remaining 4 spaces are filled in with whitespace.

Decimal Precision

You can also use String.format to specify the decimal precision of a floating-point number. For example:

let precisionString = String(format: "%.2f", 3.14159)
// precisionString is "3.14"

In the above example, %.2f specifies that the floating-point number should have 2 decimal places.

Date and Time Formatting

String.format can also be used to format dates and times. For example:

let dateString = String(format: "Today is %@.", "\(Date())")
// dateString is "Today is 2021-08-11 20:03:28 +0000."

In the above example, the default description method of the Date object is used to create a string representation of the current date and time.

Emoji

Finally, you can use String.format to add emoji to your strings. You can use Unicode code points to specify the emoji you want to use. For example:

let emojiString = String(format: "I love %@!", "\u{1F60D}")
// emojiString is "I love 😍!"

In the above example, \u{1F60D} specifies the Unicode code point for the "smiling face with heart-eyes" emoji.

Conclusion

In conclusion, String.format is a powerful function that allows you to format strings in a variety of ways. With String.format, you can easily add variables, dates, and even emoji to your strings based on your desired output.