Swift - 布林值



就像其他程式語言一樣,Swift 也支援一種稱為 bool 的布林資料型別。布林值是邏輯的,因為它們可以是“是”或“否”。布林資料型別只有兩個可能的值:truefalse。它們通常用於表達二元決策,並在控制流和決策中發揮重要作用。

語法

以下是布林變數的語法:

let value1 : Bool = true
let value2 : Bool = false

以下是布林型別的簡寫語法:

let value1 = true
let value2 = false

示例

使用布林值和邏輯語句的 Swift 程式。

import Foundation

// Defining boolean data type
let color : Bool = true

// If the color is true, then if block will execute
if color{
   print("My car color is red")
}

// Otherwise, else block will execute
else{
   print("My car color is not red")
}

輸出

My car color is red

在 Swift 中結合布林值和邏輯運算子

在 Swift 中,允許我們將布林值與邏輯運算子結合使用,例如邏輯與“&&”、邏輯或“||”和邏輯非“!”來建立更復雜的表示式。使用這些運算子,我們可以對布林值執行各種條件運算。

示例

結合布林值和邏輯運算子的 Swift 程式。

import Foundation

// Defining boolean data type
let isUsername = true
let isPassword = true
let hasAdminAccess = false
let isUserAccount = true

// Combining boolean data type with logical AND and OR operators
let finalAccess = isUsername && isPassword && (hasAdminAccess || isUserAccount)

/* If the whole expression returns true then only the
user gets access to the admin panel. */
if finalAccess {
   print("Welcome to the admin panel")
} else {
   print("You are not allowed to access admin panel")
}

輸出

Welcome to the admin panel
廣告