
- Swift 教程
- Swift - 首頁
- Swift - 概述
- Swift - 環境
- Swift - 基本語法
- Swift - 變數
- Swift - 常量
- Swift - 字面量
- Swift - 註釋
- Swift 運算子
- Swift - 運算子
- Swift - 算術運算子
- Swift - 比較運算子
- Swift - 邏輯運算子
- Swift - 賦值運算子
- Swift - 位運算子
- Swift - 其他運算子
- Swift 高階運算子
- Swift - 運算子過載
- Swift - 算術溢位運算子
- Swift - 恆等運算子
- Swift - 範圍運算子
- Swift 資料型別
- Swift - 資料型別
- Swift - 整數
- Swift - 浮點數
- Swift - Double
- Swift - 布林值
- Swift - 字串
- Swift - 字元
- Swift - 類型別名
- Swift - 可選值
- Swift - 元組
- Swift - 斷言和前提條件
- Swift 控制流
- Swift - 決策
- Swift - if 語句
- Swift - if...else if...else 語句
- Swift - if-else 語句
- Swift - 巢狀 if 語句
- Swift - switch 語句
- Swift - 迴圈
- Swift - for in 迴圈
- Swift - while 迴圈
- Swift - repeat...while 迴圈
- Swift - continue 語句
- Swift - break 語句
- Swift - fallthrough 語句
- Swift 集合
- Swift - 陣列
- Swift - 集合
- Swift - 字典
- Swift 函式
- Swift - 函式
- Swift - 巢狀函式
- Swift - 函式過載
- Swift - 遞迴
- Swift - 高階函式
- Swift 閉包
- Swift - 閉包
- Swift - 轉義和非轉義閉包
- Swift - 自動閉包
- Swift 面向物件程式設計
- Swift - 列舉
- Swift - 結構體
- Swift - 類
- Swift - 屬性
- Swift - 方法
- Swift - 下標
- Swift - 繼承
- Swift - 重寫
- Swift - 初始化
- Swift - 析構
- Swift 高階特性
- Swift - ARC 概述
- Swift - 可選鏈
- Swift - 錯誤處理
- Swift - 併發
- Swift - 型別轉換
- Swift - 巢狀型別
- Swift - 擴充套件
- Swift - 協議
- Swift - 泛型
- Swift - 訪問控制
- Swift - 函式與方法
- Swift - SwiftyJSON
- Swift - 單例類
- Swift 隨機數
- Swift 不透明型別和裝箱型別
- Swift 有用資源
- Swift - 線上編譯
- Swift - 快速指南
- Swift - 有用資源
- Swift - 討論
Swift - 布林值
就像其他程式語言一樣,Swift 也支援一種稱為 bool 的布林資料型別。布林值是邏輯的,因為它們可以是“是”或“否”。布林資料型別只有兩個可能的值:true 和 false。它們通常用於表達二元決策,並在控制流和決策中發揮重要作用。
語法
以下是布林變數的語法:
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
廣告