原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID60

关于基本操作符

Swift支持大多数的标准C操作符,也改进了其中一些能力以避免常见的编写错误。

例如,等号=并不返回一个值,以避免想用==时发生误写。运算符号(+, -, *, /, %等)会检查值的溢出并且不允许溢出,避免产生的结果超出值类型存储范围。

Swift还提供了两个范围操作符(a..<b和a...b)。

1、赋值

 let b =
var a =
a = b
// a is now equal to 10

如果赋值的右边是一个多元组, 它的元素可以马上被分解多个变量或变量:

 let (x, y) = (, )
// x is equal to 1, and y is equal to 2

与C语言和Objective-C不同, Swift的赋值操作并不返回任何值. 所以以下代码是错误的:

 if x = y {
// this is not valid, because x = y does not return a value
}

这个特性使得你无法把==错写成=, 由于if x = y是错误代码, Swift从底层帮你避免了这些代码错误.

2、算术运算符

  +        // equals 3
- // equals 2
* // equals 6
10.0 / 2.5 // equals 4.0

与C语言和Objective-C不同的是, Swift默认不允许在数值运算中出现溢出情况. 但你可以使用Swift的溢出运算符来达到你有目的的溢出, (如 a &+ b ).

加法操作 + 也用于字符串的拼接:

"hello, " + "world"  // equals "hello, world"

3、取余运算符

  %    // equals 1
- % // equals -1

求余时, b的符号会被忽略。这意味着 a % b 和 a % -b的结果是相同的.

浮点求余:

  % 2.5   // equals 0.5

注意:Swift3.0版本没有++和--运算符了。

简单的说,这两条命令没有存在的必要了,详细原因请见:Remove the ++ and -- operators

4、自增/自减运算符

i++、i--、++i、--i

与C语言中的运算符特性相同。

除非你需要使用 i++ 的特性, 不然推荐你使用 ++i 和 --i, 因为先修改后返回这样的行为更符合我们的逻辑.

4、单目负号

 let three =
let minusThree = -three // minusThree equals -3
let plusThree = -minusThree // plusThree equals 3, or "minus minus three"

单目负号写在操作数之前, 中间没有空格.

5、单目正号

单目正号就直接返回操作数的值.

let minusSix = -
let alsoMinusSix = +minusSix // alsoMinusSix equals -6

6、复合赋值

同C语言。

 var a =
a +=
// a is now equal to 3

注意,复合赋值并没有返回一个值,例如,不能写成 let b = a += 2

7、比较运算符

 ==    // true, because 1 is equal to 1
!= // true, because 2 is not equal to 1
> // true, because 2 is greater than 1
< // true, because 1 is less than 2
>= // true, because 1 is greater than or equal to 1
<= // false, because 2 is not less than or equal to 1

比较运算符经常用于控制语句,例如:

let name = "world"
if name == "world" {
print("hello, world")
} else {
print("I'm sorry \(name), but I don't recognize you")
}
// Prints "hello, world", because name is indeed equal to "world".

也可以比较两个元组,只要它们元素数目相同,并且对应元素可以相互比较。

(, "zebra") < (, "apple")   // true because 1 is less than 2
(, "apple") < (, "bird") // true because 3 is equal to 3, and "apple" is less than "bird"
(, "dog") == (, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog"

注意:Swift的标准库只能比较少于7个元素的元组,如果需要比较更多元素,你需要自己实现比较运算符。

8、三目条件运算符

 let contentHeight =
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? : )
// rowHeight is equal to 90

相当于以下代码:

 let contentHeight =
let hasHeader = true
var rowHeight = contentHeight
if hasHeader {
rowHeight = rowHeight +
} else {
rowHeight = rowHeight +
}
// rowHeight is equal to 90

三目条件运算提供有效便捷的方式来表达二选一的选择. 需要注意的是, 过度使用三目条件运算就会由简洁的代码变成难懂的代码. 我们应避免在一个组合语句使用多个三目条件运算符.

9、Nil合并运算符

 a ?? b

如果可选值a有值,则将其解包。反之,如果a等于nil,则返回默认值b。其中,a总是一个可选型的值,b则是一个与a解包的值类型一致的值。

上面的表达式可以看做下列表达式的缩写版:

 a != nil ? a! : b

下面的例子,用nil合并运算符来作默认颜色和用户自定义颜色之间的选择。

如果提供的自定义颜色名为空,则返回默认颜色。

 let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

如果自定义的颜色存在(名字符合要求),则返回自定义颜色。

 userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is not nil, so colorNameToUse is set to "green"

10、区间运算符

(1)闭区间运算符

a...b 声明了一个包含a和b的值的闭区间。a必须不大于b。

 for index in ... {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

(2)半开区间运算符

a..<b 声明了一个包含a但不包含b的半开半闭区间。a的值必须不大于b。如果a等于b,则该区间为空。

 let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in ..<count {
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

11、逻辑运算符

(1)逻辑非

 let allowedEntry = false
if !allowedEntry {
print("ACCESS DENIED")
}
// prints "ACCESS DENIED"

(2)逻辑与

 let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// prints "ACCESS DENIED"

(3)逻辑或

 let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// prints "Welcome!"

(4)组合逻辑

 if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// prints "Welcome!"

(5)显式括号增加可读性

 if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// prints "Welcome!"

Swift3.0P1 语法指南——基本操作符的更多相关文章

  1. Swift3.0P1 语法指南——构造器

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  2. Swift3.0P1 语法指南——下标

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  3. Swift3.0P1 语法指南——方法

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  4. Swift3.0P1 语法指南——属性

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  5. Swift3.0P1 语法指南——类和结构体

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  6. Swift3.0P1 语法指南——枚举

    原档: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programm ...

  7. Swift3.0P1 语法指南——闭包

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  8. Swift3.0P1 语法指南——函数

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  9. Swift3.0P1 语法指南——继承

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

随机推荐

  1. hihocoder #1112 树上的好路径

    时间限制:1000ms单点时限:1000ms内存限制:256MB 描述 现在有一棵有N个带权顶点的树,顶点编号为1,2,...,N.我们定义一条路径的次小(最小)权为它经过的所有顶点(包括起点和终点) ...

  2. AngularJs angular.identity和angular.noop

    angular.identity 函数返回本身的第一个参数.这个函数一般用于函数风格. 格式:angular.identity() 使用代码: (function () { angular.modul ...

  3. hihoCoder1284机会渺茫(唯一分解定理 + 约分)

    题目链接 #1284 : 机会渺茫 时间限制:5000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi最近在追求一名学数学的女生小Z.小Z其实是想拒绝他的,但是找不到好的说辞,于是提出 ...

  4. python 模拟登陆,请求包含cookie信息

    需求: 1.通过GET方法,访问URL地址一,传入cookie参数 2.根据地址一返回的uuid,通过POST方法,传入cooki参数 实现思路: 1.理解http的GET和POST差别 (网上有很多 ...

  5. MySQL------Navicat激活方法

    转载: http://www.jianshu.com/p/b1f9194e1e31

  6. 删除elasticsearch索引脚本

    只保留七天的索引 shell版 #!/bin/bash #hexm@ #只保留一周es日志 logName=( -nginxaccesslog -nginxerrorlog -phperrorlog ...

  7. wifi-mac

    //18:a6:f7:12:0b:8b //18:a6:f7:1e:a9:57 //18:a6:f7:1f:8e:69 //18:a6:f7:12:0b:9c //18:a6:f7:1f:cd:d4 ...

  8. Mysql事务,并发问题,锁机制

    .什么是事务 事务是一条或多条数据库操作语句的组合,具备ACID,4个特点. 原子性:要不全部成功,要不全部撤销 隔离性:事务之间相互独立,互不干扰 一致性:数据库正确地改变状态后,数据库的一致性约束 ...

  9. php返回json数据中文显示的问题

    PHP5.4版本,已经给Json新增了一个选项: JSON_UNESCAPED_UNICODE.加上这个选项后,就不会自动把中文编码了. echo json_encode("厦门" ...

  10. apt-get整理(草稿)

    1.apt-get这种方法下载的东西到哪了 参考网址:http://blog.csdn.net/magic881213/article/details/7692007 http://www.linux ...