Swift 程序演示字符串插值

swiftserver side programmingprogramming更新于 2025/9/19 20:07:17

在 Swift 中,字符串插值是一项很棒的功能,可以通过将变量、常量、函数和字面量的值直接嵌入到给定的字符串字面量中来创建新的字符串。或者说,使用字符串插值,我们可以将静态文本和动态值组合起来创建一个字符串。

语法

var myString = "hello! \(x). How are you?( 你好!)"

我们可以通过将字符串字面量、常量或变量括在一对以反斜杠 (\) 为前缀的括号中来执行字符串插值,例如 \(x)。

示例 1

在下面的 Swift 程序中,我们将演示如何执行字符串插值。首先,我们创建带有值的变量。然后,我们使用字符串插值,通过"\(varName)"将变量插入到字符串字面值中。变量的值将自动转换为字符串,并插入到指定的字符串中。

import Foundation
import Glibc

let num1 = 54
let num2 = 10
let res = num1*num2

print("The product of \(num1) and \(num2) is \(res)")

let name = "Sumonika"
let age = 23

print("Hey my name is \(name) and my age is \(age)")

输出

The product of 54 and 10 is 540
Hey my name is Sumonika and my age is 23

示例 2

在下面的 Swift 程序中,我们将演示如何执行字符串插值。首先,我们创建带有值的变量。然后,使用字符串插值,使用"\(varName)"将变量插入多行字符串字面量中。变量的值将自动转换为字符串并插入到结果字符串中。

import Foundation
import Glibc

let num1 = 54
let num2 = 10
let res = num1+num2

print("""
      Addition:
      \(num1) + \(num2) = \(res)
      """)

let name = "Novika"
let age = 23
let city = "Delhi"

print("""
      \nHey my name is \(name) 
      my age is \(age)
      I lived in \(city)
      """)

输出

Addition:
54 + 10 = 64

Hey my name is Novika 
my age is 23
I lived in Delhi

示例 3

在下面的 Swift 程序中,我们将演示如何在算术运算中执行字符串插值。首先,我们创建带有值的变量。然后使用字符串插值,使用"\(varName)"将变量插入字符串字面量中。字符串插值中定义的算术运算将执行其任务并显示结果。

import Foundation
import Glibc

let m = 19
let n = 100

let sum = "\(m) + \(n) = \(m + n)"
let difference = "\(n) - \(m) = \(n - m)"
let product = "\(n) * \(m) = \(n * m)"
let quotient = "\(m) / \(n) = \(Double(m) / Double(n))"

print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)

输出

Sum: 19 + 100 = 119
Difference: 100 - 19 = 81
Product: 100 * 19 = 1900
Quotient: 19 / 100 = 0.19

示例 4

在下面的 Swift 程序中,我们将演示如何执行布尔值插值。首先,我们创建带有值的布尔类型变量。然后,使用字符串插值将布尔值插入到插值的字符串中。布尔值将自动转换为字符串,并在插值时插入到指定的字符串中。

import Foundation
import Glibc

let isCow = true
let isGoat = false

let animal1 = "Is it cow?: \(isCow)"
let animal2 = "Is it goat?: \(isGoat)"

print(animal1)
print(animal2)

输出

Is it cow?: true
Is it goat?: false

结论

以上就是我们执行字符串插值的方法。您可以使用字符串插值来显示变量值、创建 URL、插入函数调用的值等等。字符串插值可以在单行或多行字符串字面量上执行。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部