Swift Basic Operators

Assignment Operator

The assignment operator (a = b) initializes or updates the value of a with the value of b:

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

If the right side of the assignment is a tuple with multiple values, its elements can be decomposed into multiple constants or variables at once:

let (x, y) = (1, 2)

// x is equal to 1, and y is equal to 2

Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. The following statement is not valid:

if x = y {

// This is not valid, because x = y does not return a value.

}

This feature prevents the assignment operator (=) from being used by accident when the equal to operator (==) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code.

Arithmetic Operators
Swift supports the four standard arithmetic operators for all number types:
Addition (+)

Subtraction (-)

Multiplication (*)

Division (/)

1 + 2 // equals 3

5 - 3 // equals 2

2 * 3 // equals 6

10.0 / 2.5 // equals 4.0

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default. You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b). See Overflow Operators.
The addition operator is also supported for String
concatenation:

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

Remainder Operator

The remainder operator (a % b) works out how many multiples of b will fit inside a
and returns the value that is left over (known as the remainder).

Here’s how the remainder operator works. To calculate 9 % 4
, you first work out how many 4
s will fit inside 9:


image: ../Art/remainderInteger_2x.png
image: ../Art/remainderInteger_2x.png

You can fit two 4s inside 9, and the remainder is 1 (shown in orange).In Swift, this would be written as:

9 % 4 // equals 1

To determine the answer for a % b, the % operator calculates the following equation and returns remainder as its output:

a = (b x some multiplier) + remainder

where some multiplier is the largest number of multiples of b that will fit inside a.
Inserting 9 and 4 into this equation yields:
9 = (4 x 2) + 1

The same method is applied when calculating the remainder for a negative value of a:

-9 % 4 // equals -1

Inserting -9 and 4
into the equation yields:

-9 = (4 x -2) + -1

giving a remainder value of -1.

The sign of b is ignored for negative values of b. This means that a % b and a % -b always give the same answer.

Unary Minus Operator

The sign of a numeric value can be toggled using a prefixed -, known as the unary minus operator:

let three = 3

let minusThree = -three // minusThree equals -3

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

The unary minus operator (-) is prepended directly before the value it operates on, without any white space.

Unary Plus Operator
The unary plus operator (+) simply returns the value it operates on, without any change:

let minusSix = -6

let alsoMinusSix = +minusSix // alsoMinusSix equals -6

Although the unary plus operator doesn’t actually do anything, you can use it to provide symmetry in your code for positive numbers when also using the unary minus operator for negative numbers.

Compound Assignment Operators
Like C, Swift provides compound assignment operators that combine assignment (=) with another operation. One example is the addition assignment operator (+=):

var a = 1

a += 2

// a is now equal to 3

The expression a += 2 is shorthand for a = a + 2. Effectively, the addition and the assignment are combined into one operator that performs both tasks at the same time.

Comparison Operators

Swift supports all standard C comparison operators:

  • Equal to (a == b)

  • Not equal to (a != b)

  • Greater than (a > b)

  • Less than (a < b)

  • Greater than or equal to (a >= b)

  • Less than or equal to (a <= b)

Each of the comparison operators returns a Bool value to indicate whether or not the statement is true:

1 == 1 // true because 1 is equal to 1

2 != 1 // true because 2 is not equal to 1

2 > 1 // true because 2 is greater than 1

1 < 2 // true because 1 is less than 2

1 >= 1 // true because 1 is greater than or equal to 1

2 <= 1 // false because 2 is not less than or equal to 1

Comparison operators are often used in conditional statements, such as the if statement:

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".

Ternary Conditional Operator
The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2
. It is a shortcut for evaluating one of two expressions based on whether question
is true or false. If question
is true, it evaluates answer1
and returns its value; otherwise, it evaluates answer2
and returns its value.
The ternary conditional operator is shorthand for the code below:

if question {

answer1

} else {

answer2

}

Here’s an example, which calculates the height for a table row. The row height should be 50 points taller than the content height if the row has a header, and 20 points taller if the row doesn’t have a header:

let contentHeight = 40

let hasHeader = true

let rowHeight = contentHeight + (hasHeader ? 50 : 20)

// rowHeight is equal to 90

The preceding example is shorthand for the code below:
let contentHeight = 40

let hasHeader = true

let rowHeight: Int

if hasHeader {

  rowHeight = contentHeight + 50

} else {

  rowHeight = contentHeight + 20

}

// rowHeight is equal to 90

Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
The nil-coalescing operator is shorthand for the code below:

a != nil ? a! : b

The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b
otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.

The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name:

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"

The userDefinedColorName variable is defined as an optional String, with a default value of nil. Because userDefinedColorName is of an optional type, you can use the nil-coalescing operator to consider its value. In the example above, the operator is used to determine an initial value for a String variable called colorNameToUse. Because userDefinedColorName is nil, the expression userDefinedColorName ?? defaultColorName returns the value of defaultColorName, or "red".
If you assign a non-nil value to userDefinedColorName and perform the nil-coalescing operator check again, the value wrapped inside userDefinedColorName is used instead of the default:

userDefinedColorName = "green"

colorNameToUse = userDefinedColorName ?? defaultColorName

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

Range Operators

Swift includes two range operators, which are shortcuts for expressing a range of values.
Closed Range Operator
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
The closed range operator is useful when iterating over a range in which you want all of the values to be used, such as with a for -in loop:

for index in 1...5 {

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

Half-Open Range Operator

The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b. It is said to be half-openbecause it contains its first value, but not its final value. As with the closed range operator, the value of a must not be greater than b. If the value of a is equal to b, then the resulting range will be empty.Half-open ranges are particularly useful when you work with zero-based lists such as arrays, where it is useful to count up to (but not including) the length of the list:

let names = ["Anna", "Alex", "Brian", "Jack"]

let count = names.count

for i in 0..<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

Logical Operators

Logical operators modify or combine the Boolean logic values true
and false
. Swift supports the three standard logical operators found in C-based languages:
Logical NOT (!a
)

Logical AND (a && b
)

Logical OR (a || b
)

Logical NOT Operator

The logical NOT operator (!a
) inverts a Boolean value so that true
becomes false
, and false
becomes true
.
The logical NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space. It can be read as “not a
”, as seen in the following example:
let allowedEntry = false

if !allowedEntry {

print("ACCESS DENIED")

}

// Prints "ACCESS DENIED"

The phrase if !allowedEntry
can be read as “if not allowed entry.” The subsequent line is only executed if “not allowed entry” is true; that is, if allowedEntry
is false
.
As in this example, careful choice of Boolean constant and variable names can help to keep code readable and concise, while avoiding double negatives or confusing logic statements.

Logical AND Operator

The logical AND operator (a && b
) creates logical expressions where both values must be true
for the overall expression to also be true
.
If either value is false
, the overall expression will also be false
. In fact, if the first value is false
, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate to true
. This is known as short-circuit evaluation.
This example considers two Bool
values and only allows access if both values are true
:

let enteredDoorCode = true

let passedRetinaScan = false

if enteredDoorCode && passedRetinaScan {

print("Welcome!")

} else {

print("ACCESS DENIED")

}

// Prints "ACCESS DENIED"

Logical OR Operator
The logical OR operator (a || b
) is an infix operator made from two adjacent pipe characters. You use it to create logical expressions in which only one of the two values has to be true
for the overall expression to be true
.
Like the Logical AND operator above, the Logical OR operator uses short-circuit evaluation to consider its expressions. If the left side of a Logical OR expression is true
, the right side is not evaluated, because it cannot change the outcome of the overall expression.
In the example below, the first Bool
value (hasDoorKey
) is false
, but the second value (knowsOverridePassword
) is true
. Because one value is true
, the overall expression also evaluates to true
, and access is allowed:

let hasDoorKey = false

let knowsOverridePassword = true

if hasDoorKey || knowsOverridePassword {

print("Welcome!")

} else {

print("ACCESS DENIED")

}

// Prints "Welcome!"

Combining Logical Operators

You can combine multiple logical operators to create longer compound expressions:

if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {

print("Welcome!")

} else {

print("ACCESS DENIED")

}

// Prints "Welcome!"

Explicit Parentheses

It is sometimes useful to include parentheses when they are not strictly needed, to make the intention of a complex expression easier to read. In the door access example above, it is useful to add parentheses around the first part of the compound expression to make its intent explicit:

if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {

print("Welcome!")

} else {

print("ACCESS DENIED")

}

// Prints "Welcome!"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,924评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,781评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,813评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,264评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,273评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,383评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,800评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,482评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,673评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,497评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,545评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,240评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,802评论 3 304
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,866评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,101评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,673评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,245评论 2 341

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,325评论 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,422评论 5 6
  • 早晨叫小儿子起床,他闭着眼睛轻声说,妈妈让我作完这个梦再起来好吗?于是静静地等,看着他小小的身体舒舒服服地缩在被窝...
    我爱我de家阅读 620评论 0 1
  • 转: 首先,前端/页编人员主要负责站内优化,主要从四个方面入手: 第一个,站内结构优化 合理规划站点结构(1、扁平...
    bianji阅读 519评论 0 4
  • 走的时候,天已入凉,换上秋装 去到那里,天还湿热,换上夏衣 我说,此时回家,该是避暑 中秋 连绵的阴雨,断断续续下...
    驸惋阅读 155评论 0 0