Swift 程式演示字串插值


在 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、插值來自函式呼叫的值等。字串插值可以在單行或多行字串字面量上執行。

更新於: 2023年6月13日

155 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.