逻辑运算符 #

一、逻辑运算符概述 #

Swift支持三种逻辑运算符:

运算符 名称 描述
!a 逻辑非 取反
a && b 逻辑与 都为真才为真
a || b 逻辑或 有一个为真就为真

二、逻辑非(!) #

2.1 基本用法 #

swift
let isTrue = true
let isFalse = !isTrue

print(isTrue)
print(isFalse)

2.2 条件取反 #

swift
let isLoggedIn = false

if !isLoggedIn {
    print("请先登录")
}

2.3 双重否定 #

swift
let hasPermission = true

if !!hasPermission {
    print("有权限")
}

if hasPermission {
    print("有权限")
}

2.4 实际应用 #

swift
let text = ""

if !text.isEmpty {
    print("文本不为空")
} else {
    print("文本为空")
}

三、逻辑与(&&) #

3.1 基本用法 #

swift
let a = true
let b = true
let c = false

print(a && b)
print(a && c)
print(c && c)

3.2 真值表 #

a b a && b
true true true
true false false
false true false
false false false

3.3 多条件判断 #

swift
let age = 25
let hasID = true
let hasTicket = true

if age >= 18 && hasID && hasTicket {
    print("可以进入")
}

3.4 短路求值 #

swift
func checkCondition1() -> Bool {
    print("检查条件1")
    return true
}

func checkCondition2() -> Bool {
    print("检查条件2")
    return false
}

let result = checkCondition1() && checkCondition2()
print("结果: \(result)")

四、逻辑或(||) #

4.1 基本用法 #

swift
let a = true
let b = false
let c = false

print(a || b)
print(b || c)
print(a || a)

4.2 真值表 #

a b a || b
true true true
true false true
false true true
false false false

4.3 多条件判断 #

swift
let isVIP = false
let hasCoupon = true
let isFirstPurchase = false

if isVIP || hasCoupon || isFirstPurchase {
    print("可以享受优惠")
}

4.4 短路求值 #

swift
func checkA() -> Bool {
    print("检查A")
    return true
}

func checkB() -> Bool {
    print("检查B")
    return false
}

let result = checkA() || checkB()
print("结果: \(result)")

五、组合使用 #

5.1 混合运算 #

swift
let a = true
let b = false
let c = true

let result = a && b || c
print(result)

let result2 = a && (b || c)
print(result2)

5.2 复杂条件 #

swift
let age = 25
let isStudent = false
let isVIP = true
let hasCoupon = false

if (age >= 18 && isStudent) || isVIP || hasCoupon {
    print("符合条件")
}

5.3 使用括号明确优先级 #

swift
let a = true
let b = false
let c = true

let result1 = a || b && c
let result2 = (a || b) && c

print(result1)
print(result2)

六、运算符优先级 #

6.1 逻辑运算符优先级 #

优先级从高到低:

  1. !(逻辑非)
  2. &&(逻辑与)
  3. ||(逻辑或)
swift
let a = true
let b = false
let c = true

let result = !a || b && c
print(result)

let result2 = (!a) || (b && c)
print(result2)

6.2 与比较运算符结合 #

swift
let score = 85
let attendance = 90

if score >= 60 && attendance >= 80 {
    print("课程通过")
}

七、实际应用 #

7.1 用户验证 #

swift
func validateUser(username: String?, password: String?) -> Bool {
    guard let username = username,
          let password = password,
          !username.isEmpty,
          !password.isEmpty,
          password.count >= 8 else {
        return false
    }
    return true
}

print(validateUser(username: "admin", password: "12345678"))
print(validateUser(username: "", password: "12345678"))

7.2 权限检查 #

swift
enum UserRole {
    case admin
    case editor
    case viewer
}

func canEdit(role: UserRole, isOwner: Bool) -> Bool {
    return role == .admin || role == .editor || isOwner
}

print(canEdit(role: .viewer, isOwner: true))
print(canEdit(role: .viewer, isOwner: false))

7.3 表单验证 #

swift
struct FormData {
    var name: String
    var email: String
    var age: Int
    var termsAccepted: Bool
}

func validateForm(_ data: FormData) -> Bool {
    let isNameValid = !data.name.isEmpty && data.name.count >= 2
    let isEmailValid = data.email.contains("@")
    let isAgeValid = data.age >= 18 && data.age <= 120
    let isTermsAccepted = data.termsAccepted
    
    return isNameValid && isEmailValid && isAgeValid && isTermsAccepted
}

let form = FormData(name: "张三", email: "test@example.com", age: 25, termsAccepted: true)
print(validateForm(form))

7.4 搜索过滤 #

swift
struct Product {
    var name: String
    var price: Double
    var inStock: Bool
    var category: String
}

let products = [
    Product(name: "iPhone", price: 999, inStock: true, category: "手机"),
    Product(name: "MacBook", price: 1999, inStock: false, category: "电脑"),
    Product(name: "iPad", price: 599, inStock: true, category: "平板")
]

func filterProducts(products: [Product], minPrice: Double?, maxPrice: Double?, inStockOnly: Bool) -> [Product] {
    return products.filter { product in
        let priceValid = (minPrice == nil || product.price >= minPrice!) &&
                        (maxPrice == nil || product.price <= maxPrice!)
        let stockValid = !inStockOnly || product.inStock
        return priceValid && stockValid
    }
}

let filtered = filterProducts(products: products, minPrice: 500, maxPrice: 1500, inStockOnly: true)
filtered.forEach { print($0.name) }

八、最佳实践 #

8.1 使用有意义的变量名 #

swift
let isLoggedIn = true
let hasPermission = true
let isAccountActive = true

if isLoggedIn && hasPermission && isAccountActive {
    print("可以访问")
}

8.2 提前返回 #

swift
func process(user: User?) {
    guard let user = user,
          user.isActive,
          user.hasPermission else {
        return
    }
    
    print("处理用户: \(user.name)")
}

8.3 避免复杂条件 #

swift
if (user.age >= 18 && user.hasID) || user.isVIP || user.hasSpecialPermission {
    print("允许访问")
}

let isAdult = user.age >= 18 && user.hasID
let hasSpecialAccess = user.isVIP || user.hasSpecialPermission

if isAdult || hasSpecialAccess {
    print("允许访问")
}

九、总结 #

本章学习了Swift的逻辑运算符:

  • 逻辑非(!):取反操作
  • 逻辑与(&&):都为真才为真
  • 逻辑或(||):有一个为真就为真
  • 短路求值:优化性能

最佳实践:

  • 使用括号明确优先级
  • 使用有意义的布尔变量名
  • 避免过于复杂的条件表达式
  • 利用短路求值优化性能

下一章,我们将学习位运算符!

最后更新:2026-03-26