分类 标签 存档 黑客派 订阅 搜索

Swift 基本运算符

85 浏览

赋值运算符

//a = b
let b = 10
var a = 5
a = b

var (x, y) = (1, 2)
print(x)

//if x = y {
    //错误,因为x = y并不返回任何值
//}

算术运算符

//+ - * / %
1 + 2
5 - 3
2 * 3
10.0 / 2.5
"hello,"+"world!"

9 % 4
-9 % 4
8 % 2.5

//一元负号运算符
let three = 3
let minusThree = -three
let plusThree = -minusThree

//一元正号运算符
let minusSix = -6
let alsoMinusSix = +minusSix//alsoMinusSix = -6,没什么卵用,跟-号同用时,代码对称美.

组合赋值运算符

//+= -=
var c = 1
c += 2 //c 是3

比较运算符

// == != > < >= <= 
//===(恒等) 跟 !==(恒不等) 判断两个引用是否指向同一个对象
1 == 1 //true
2 != 1 //true
2 > 1 //true
1 < 2 //true
1 >= 1 //true
2 <= 1 //false
let name = "world"
if name == "world" {
    print("hello, world")
} else {
    print("I'm sorry \(name), but I don't recognize you")
}
(1, "z") < (2, "apple") //元组比较,从左到右,逐值比较.true,因为1 小于 2
(3, "a") < (3, "b")//true,因为a 小于 b
(4, "dog") == (4, "dog")//true,因为4 等于 4,dog 等于 dog

三目运算符

//a ? b : c
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)//rowHeight 为 90

空合运算符

//a ?? b  //a为可选类型
let defaultColorName = "color"
var userDefineColorName :String? //默认值为nil
var colorNameToUse = userDefineColorName ?? defaultColorName//已经强制解封
print("\(colorNameToUse)")//red,已经解封
userDefineColorName = "green"
colorNameToUse = userDefineColorName ?? defaultColorName
print("\(colorNameToUse)")//green,已经解封

区间运算符

//a...b => >=a&&<=b   a..<b >=a&&<b
//闭区间运算符
for index in 1...5 {
    print("\(index) * 5 = \(index * 5)")
}

//半开区间运算符
let names = ["Anna", "Alex", "Brian", "Jack"]
for index in 0..<names.count {
    print("第\(index + 1) 个人叫 \(names[index])")
}

逻辑运算符

//! && ||
//逻辑非 !
let allowEntry = false
if !allowEntry {
    print("ACCESS DENIED")
}
//逻辑与 a && b
let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
    print("Welcome!")
} else {
    print("ACCESS DENIED") //输出ACCESS DENIED
}
//逻辑或 a || b
let hasDoorKey = false
let knowOverridePassword = true
if hasDoorKey || knowOverridePassword {
    print("Welcome!") //输出Welcome!
} else {
    print("ACCESS DENIED")
}

//逻辑运算符组合计算
//从左到右两两计算,别忘了短路计算
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowOverridePassword {
    print("Welcome!") //输出Welcome!
} else {
    print("ACCESS DENIED")
}

//使用括号来明确优先级
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowOverridePassword {
    print("Welcome!") //输出Welcome!,这加不加括号一个样,因为是加在头两个
} else {
    print("ACCESS DENIED")
}

原文地址, 非常感谢翻译者的持续更新.

--EOF--

评论  
留下你的脚步
推荐阅读